Haskell Permutations Module


SUBMITTED BY: Guest

DATE: March 5, 2014, 6:52 a.m.

FORMAT: Text only

SIZE: 2.0 kB

HITS: 985

  1. module Permutations where
  2. fact n = foldl (*) 1 [2..n]
  3. del k xs = [x | x <- xs, x /= k]
  4. count p xs = length [x | x <- xs, p x]
  5. --The number of the permutation in lexicographical order. Usage example: lexNumOfPerm [2, 4, 3, 1]
  6. lexNumOfPerm [] = 1
  7. lexNumOfPerm (x:xs) = lexNumOfPerm xs + count (< x) xs * fact (length xs)
  8. lexPerm' k acc [] = acc
  9. lexPerm' k acc xs = lexPerm' (k `mod` nf) (mark:acc)(del mark xs) where
  10. mark = xs !! (k `div` nf)
  11. nf = fact (length xs - 1)
  12. --The k-th permutation in lexicographical order. Usage example: lexPerm 12 [1, 2, 3, 4]
  13. lexPerm k = reverse . lexPerm' (k - 1) []
  14. --The k-th permutation in lexicographical order. Usage example: revLexPerm 12 [1, 2, 3, 4]
  15. revLexPerm k xs = lexPerm' (k - 1) [] (reverse xs)
  16. fikePlaceVals n = foldl (\(x:xs) p -> p*x : x : xs) [1] [n, n - 1.. 3]
  17. dSeq k n = reverse $ tail $ foldl (\(x:xs) p -> (mod x p) : (div x p) : xs) [k - 1] (fikePlaceVals n)
  18. fikeSeq k n = zipWith (-) [1..n] (dSeq k $ n)
  19. swap i j list | i == j = list
  20. | i < j = hs ++ (y:xs) ++ (x:ys)
  21. | otherwise = swap j i list where
  22. (hs, zs) = splitAt i list
  23. (x:xs, y:ys) = splitAt (j - i) zs
  24. --The k-th permutation in Fike's order. Usage example: fikePerm 12 [1, 2, 3, 4]
  25. fikePerm k marks = snd (foldl (\(i, p) j -> (i + 1, swap i j p)) (1, marks) $ fikeSeq k (length marks))
  26. --Powerset of a set. Usage example: powerSet [1, 2, 3, 4]
  27. powerSet [] = [[]];
  28. powerSet (x:xs) = pXs ++ [x:ys | ys <- pXs] where pXs = powerSet xs
  29. setFromBits _ 0 = []; setFromBits (x:xs) bits = if (bits `mod` 2 == 0) then setFromBits xs (bits `div` 2) else x : setFromBits xs (bits `div` 2)
  30. --Powerset of a set using setFromBits
  31. powerSet' set = map (setFromBits set) [0.. 2^n -1] where n = length set
  32. --nCr
  33. comb n r = foldl (*) 1 [n, n - 1 .. n - r + 1] `div` foldl (*) 1 [2..r]

comments powered by Disqus