Last active
August 29, 2015 14:08
-
-
Save adamse/dc131e1eed9027102528 to your computer and use it in GitHub Desktop.
Shuffle vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Shuffle where | |
import Control.Monad | |
import Control.Monad.ST | |
import System.Random | |
import qualified Data.Vector as V | |
import qualified Data.Vector.Mutable as MV | |
-- | Shuffles a vector in linear time using inside out Fisher-Yates. | |
-- | |
-- Returns a new vector. | |
shuffle :: RandomGen g => g -> V.Vector a -> V.Vector a | |
shuffle gen src = runST $ do | |
a <- MV.new n | |
foldM_ | |
(\g i -> do | |
let (j, g') = randomR (0, i) g | |
unless (i == j) | |
(MV.read a j >>= MV.write a i) | |
MV.write a j (src V.! i) | |
return g' | |
) gen [0 .. n - 1] | |
V.unsafeFreeze a -- safe since we never use a again | |
where | |
n = V.length src |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment