tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
|
|
@ -0,0 +1,25 @@
|
|||
import Control.Monad
|
||||
import Data.List
|
||||
|
||||
-- Compute all derangements of a list
|
||||
derangements xs = filter (and . zipWith (/=) xs) $ permutations xs
|
||||
|
||||
-- Compute the number of derangements of n elements
|
||||
subfactorial 0 = 0
|
||||
subfactorial 1 = 0
|
||||
subfactorial 2 = 1
|
||||
subfactorial n = (n-1) * (subfactorial (n-1) + subfactorial (n-2))
|
||||
|
||||
main = do
|
||||
-- Generate and show all the derangements of four integers
|
||||
print $ derangements [1..4]
|
||||
putStrLn ""
|
||||
|
||||
-- Print the count of derangements vs subfactorial
|
||||
forM_ [1..9] $ \i ->
|
||||
putStrLn $ show (length (derangements [1..i])) ++ " " ++
|
||||
show (subfactorial i)
|
||||
putStrLn ""
|
||||
|
||||
-- Print the number of derangements in a list of 20 items
|
||||
print $ subfactorial 20
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
derangements xs = loop xs xs
|
||||
where loop [] [] = [[]]
|
||||
loop (h:hs) xs = [x:ys | x <- xs, x /= h, ys <- loop hs (delete x xs)]
|
||||
Loading…
Add table
Add a link
Reference in a new issue