Permutations/Derangements: Difference between revisions

(Added Kotlin)
Line 1,005:
=={{header|Haskell}}==
 
<lang Haskell>import Control.Monad (forM_)
 
import Data.List (permutations)
 
-- Compute all derangements of a list
derangements xs:: =Eq filtera (and . zipWith (/=) xs)> $[a] permutations-> xs[[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))
 
main =:: doIO ()
main
-- Generate and show all the derangements of four integers
-- Generate printand $show all the derangements [1..4]of four integers
= do
print $ derangements [1 .. 4]
putStrLn ""
 
-- Print the count of derangements vs subfactorial
forM_ [1 .. 9] $ \i ->
\i ->
putStrLn $ show (length (derangements [1..i])) ++ " " ++
putStrLn $
show (subfactorial 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</lang>
{{outOut}}
 
<pre>[[4,3,2,1],[3,4,2,1],[2,3,4,1],[4,1,2,3],[2,4,1,3],[2,1,4,3],[4,3,1,2],[3,4,1,2],[3,1,4,2]]
{{out}}
<pre>
[[4,3,2,1],[3,4,2,1],[2,3,4,1],[4,1,2,3],[2,4,1,3],[2,1,4,3],[4,3,1,2],[3,4,1,2],[3,1,4,2]]
 
0 0
Line 1,044 ⟶ 1,046:
133496 133496
 
895014631192902121</pre>
</pre>
 
Alternatively, this is a backtracking method:
9,655

edits