Advertisement
ostankino_tower

Gray codes

Aug 10th, 2020 (edited)
1,906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- naryGrayCodes from hackage
  2. naryGrayCodes :: [a] -> Int -> [[a]]
  3. naryGrayCodes xs 1 = map (\x -> [x]) xs
  4. naryGrayCodes xs k = snd $ foldl prefixAndShift (ys,[]) zs
  5.   where ys = naryGrayCodes xs 1
  6.         zs = naryGrayCodes xs (k-1)
  7.  
  8. -- | Shift elements right.
  9. shift :: [a] -> [a]
  10. shift as = last as : init as
  11.  
  12. prefixAndShift :: ([[a]],[[a]]) -> [a] -> ([[a]],[[a]])
  13. prefixAndShift (ys,zs) xs = (shift ys, zs ++ (map (xs++) ys))
  14.  
  15. l = "0123456789"
  16.  
  17. dumb = [[x,y,z] | x<-l, y<-l, z<-l]
  18. gray = naryGrayCodes l 3
  19.  
  20.  
  21. scanlx f xs = go f xs []
  22.   where
  23.     go f [x1, x2]   acc = (f x1 x2):acc
  24.     go f (x1:x2:xs) acc = go f (x2:xs) ((f x1 x2):acc)
  25.  
  26. scanlx2 f xs = zipWith f xs (tail xs)
  27.  
  28. hamd xs ys = go xs ys 0
  29.    where
  30.       go []     []     acc = acc
  31.       go (x:xs) (y:ys) acc = go xs ys (if x==y then acc else acc+1)
  32.  
  33. hamd2 xs ys = length (filter id (zipWith (/=) xs ys))
  34.  
  35. main = putStrLn $ unlines $ map show $ zip3 [1..] dumb gray
  36. --main = putStrLn $ show $ map sum $ map (scanlx hamd) $ [dumb, gray]
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement