RosettaCodeData/Task/Permutations-Derangements/Haskell/permutations-derangements-1.hs

34 lines
843 B
Haskell
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
import Control.Monad (forM_)
import Data.List (permutations)
2013-04-10 23:57:08 -07:00
-- Compute all derangements of a list
2017-09-23 10:01:46 +02:00
derangements
:: Eq a
=> [a] -> [[a]]
derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations
2013-04-10 23:57:08 -07:00
-- Compute the number of derangements of n elements
2017-09-23 10:01:46 +02:00
subfactorial
:: (Eq a, Num a)
=> a -> a
2016-12-05 22:15:40 +01:00
subfactorial 0 = 1
2013-04-10 23:57:08 -07:00
subfactorial 1 = 0
2017-09-23 10:01:46 +02:00
subfactorial n = (n - 1) * (subfactorial (n - 1) + subfactorial (n - 2))
2013-04-10 23:57:08 -07:00
2017-09-23 10:01:46 +02:00
main :: IO ()
main
-- Generate and show all the derangements of four integers
= do
print $ derangements [1 .. 4]
2013-04-10 23:57:08 -07:00
putStrLn ""
-- Print the count of derangements vs subfactorial
2017-09-23 10:01:46 +02:00
forM_ [1 .. 9] $
\i ->
putStrLn $
mconcat
[show (length (derangements [1 .. i])), " ", show (subfactorial i)]
2013-04-10 23:57:08 -07:00
putStrLn ""
-- Print the number of derangements in a list of 20 items
print $ subfactorial 20