Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

random order

Name: Anonymous 2008-05-24 2:19

What is an efficient way to randomize the order of something, for example characters in a string or places in an array, without repeating anything before you ran trough all characters/arrayplaces?

Name: Anonymous 2008-05-24 14:30

>>8
With the right type signature, >>6 is actually O(n) if use it on a DiffArray.

import Monad
import Random
import Data.Array.IArray

randomize :: (IArray a e, Enum i, Random i, Ix i) => a i e -> IO (a i e)
randomize array =
   foldM step array $ reverse [lo..hi]
   where step a i = fmap (swap a i) $ randomRIO (lo, i)
         swap a i j = a // [(j, a!i), (i, a!j)]
         (lo, hi) = bounds array

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List