Topswops: Difference between revisions
→{{header|Haskell}}: Fractionally faster using <*> to dispense with an extra [1..] for derangements zipWith
(Added Kotlin) |
(→{{header|Haskell}}: Fractionally faster using <*> to dispense with an extra [1..] for derangements zipWith) |
||
Line 885:
=={{header|Haskell}}==
====Searching permutations====
<lang Haskell>import Data.List (permutations)
Line 910 ⟶ 911:
10: 38</pre>
====Searching derangements====
'''Alternate version'''
<br>Uses only permutations with all elements out of place.
<lang Haskell>import Data.List (permutations, inits)
import Control.Arrow▼
▲import Control.Arrow (first)
derangements = filter (and . zipWith (/=) [1..] ). permutations▼
topswop = ((uncurry (++). first reverse).). splitAt▼
derangements :: [Int] -> [[Int]]
topswopIter = takeWhile((/=1).head). iterate (topswop =<< head)▼
swops = map (length. topswopIter). derangements▼
topswop :: Int -> [a] -> [a]
▲topswop = ((uncurry (++) . first reverse) .) . splitAt
topswopIter :: [Int] -> [[Int]]
▲topswopIter = takeWhile ((/= 1) . head) . iterate (topswop =<< head)
swops :: [Int] -> [Int]
topSwops :: [Int] -> [(Int, Int)]
topSwops = zip [1 ..] .
main :: IO ()
main = mapM_ print $ take 10 $ topSwops [1 ..]</lang>
'''Output'''
<pre>*Main> mapM_ print $ take 10 $ topSwops [1..]
|