Skip to content

Instantly share code, notes, and snippets.

@adityam
Created March 5, 2011 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adityam/856072 to your computer and use it in GitHub Desktop.
Save adityam/856072 to your computer and use it in GitHub Desktop.
Josephus problem
import Data.Sequence as Seq
import System.Environment
survivor :: Int -> [a] -> a
survivor k soldiers = viewnext k (Seq.fromList soldiers)
where
viewnext l list = killnext l (Seq.viewl list)
killnext l (x:<xs) | Seq.null xs = x
| l == 1 = viewnext k xs
| otherwise = viewnext (l-1) (xs|>x)
main = do
args <- getArgs
let k = read (args!!0) :: Int
n = read (args!!1) :: Int
print $ survivor k [1..n]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment