Advertisement
karlicoss

permutations

Sep 6th, 2012
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.List as List
  2.  
  3. makePairs :: [Int] -> [(Int, [Int])]
  4. makePairs [] = []
  5. makePairs l = map (\x -> (x, filter (/= x) l)) l
  6.  
  7. mapFst :: (a -> b) -> [(a, c)] -> [(b, c)]
  8. mapFst _ [] = []
  9. mapFst f ((x, y): xs) = (f x, y): (mapFst f xs)
  10.  
  11. mapSnd :: (a -> b) -> [(c, a)] -> [(c, b)]
  12. mapSnd _ [] = []
  13. mapSnd f ((x, y): xs) = (x, f y): (mapSnd f xs)
  14.  
  15. flatMap :: (a -> b -> b) -> [(a, [b])] -> [b]
  16. flatMap _ [] = []
  17. flatMap f (x: xs) = (map (f $ fst x) (snd x)) ++ flatMap f xs
  18.  
  19. genPermutationHelper :: [Int] -> [[Int]]
  20. genPermutationHelper [] = [[]]
  21. genPermutationHelper s = applied where
  22.     pairs = makePairs s
  23.     unapplied = mapSnd genPermutationHelper pairs
  24.     applied = flatMap (\x l -> x:l) unapplied
  25.  
  26. genPermutations :: Int -> [[Int]]
  27. genPermutations n = genPermutationHelper [1..n]
  28.  
  29.  
  30. showList' :: (Show a) => [a] -> String
  31. showList' [] = ""
  32. showList' l = concat $ List.intersperse " " (map show l)
  33.  
  34. main = do
  35.     s <- getLine
  36.     let n = read s :: Int
  37.     let permutations = genPermutations n
  38.     print $ length permutations
  39.     sequence_ $ map (putStrLn . showList') permutations
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement