Skip to content

Instantly share code, notes, and snippets.

@ahammar
Created February 17, 2014 23:20
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 ahammar/9061298 to your computer and use it in GitHub Desktop.
Save ahammar/9061298 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle
{-# LANGUAGE BangPatterns #-}
import System.Random
shuffle :: [a] -> Int -> IO [a]
shuffle xs 1 = return xs
shuffle !xs !k = do
i <- getStdRandom (randomR (0 , k - 1))
shuffle (sswap i k xs) (k - 1)
sswap :: Int -> Int -> [a] -> [a]
sswap !i !j !xs = take i xs ++ [xs !! j] ++ (take (j - i - 1) $ drop (i + 1) xs) ++ [xs !! i] ++ drop (j + 1) xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment