praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Foo.hs (965B)


      1 -- First, find the first non-repeated element in an unsorted array. For
      2 -- instance, in the array [3, 5, 3, 2, 1], element 3 is repeated, elements 5,
      3 -- 2, and 1 are non-repeated, and the first of those is 5. Second, find the
      4 -- first element that appears an even number of times in an unsorted array. For
      5 -- instance, in the array [5, 3, 5, 1, 5, 1, 3], elements 1 and 3 appear an
      6 -- even number of times, and the first of those is 3.
      7 
      8 import Data.Function
      9 import Data.List
     10 import qualified Data.Map.Strict as MS
     11 import qualified Data.Set as S
     12 
     13 one :: Ord a => [a] -> a
     14 one =
     15     snd
     16   . minimumBy (compare `on` fst)
     17   . concat
     18   . filter ((< 2) . length)
     19   . groupBy ((==) `on` snd)
     20   . sortBy (compare `on` snd) . zip [1..]
     21 
     22 two :: Ord a => [a] -> a
     23 two =
     24     snd
     25   . minimumBy (compare `on` fst)
     26   . concat
     27   . filter (even . length)
     28   . groupBy ((==) `on` snd)
     29   . sortBy (compare `on` snd) . zip [1..]
     30 
     31 test0 = [3, 5, 3, 2, 1]
     32 test1 = [5, 3, 5, 1, 5, 1, 3]
     33 
     34