RosettaCodeData/Task/Josephus-problem/Haskell/josephus-problem-2.hs

17 lines
403 B
Haskell
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
jseq :: Int -> Int -> [Int]
jseq n k = f n [1 .. n]
where
2013-06-05 21:47:54 +00:00
f 0 _ = []
2017-09-23 10:01:46 +02:00
f m s = x : f (m - 1) (right ++ left)
where
(left, x:right) = splitAt (mod (k - 1) m) s
2013-06-05 21:47:54 +00:00
-- the final survivor is ((k + ...((k + ((k + 0)`mod` 1)) `mod` 2) ... ) `mod` n)
2017-09-23 10:01:46 +02:00
jos :: Int -> Int -> Int
jos n k = 1 + foldl (mod . (k +)) 0 [2 .. n]
2013-06-05 21:47:54 +00:00
2017-09-23 10:01:46 +02:00
main :: IO ()
2013-06-05 21:47:54 +00:00
main = do
2017-09-23 10:01:46 +02:00
print $ jseq 41 3
print $ jos 10000 100