September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -1,24 +1,33 @@
import Control.Monad
import Data.List
import Control.Monad (forM_)
import Data.List (permutations)
-- Compute all derangements of a list
derangements xs = filter (and . zipWith (/=) xs) $ permutations xs
derangements
:: Eq a
=> [a] -> [[a]]
derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations
-- Compute the number of derangements of n elements
subfactorial
:: (Eq a, Num a)
=> a -> a
subfactorial 0 = 1
subfactorial 1 = 0
subfactorial n = (n-1) * (subfactorial (n-1) + subfactorial (n-2))
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]
main :: IO ()
main
-- Generate and show all the derangements of four integers
= do
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)
forM_ [1 .. 9] $
\i ->
putStrLn $
mconcat
[show (length (derangements [1 .. i])), " ", show (subfactorial i)]
putStrLn ""
-- Print the number of derangements in a list of 20 items
print $ subfactorial 20