Problem 25

99 Haskell Problems

Problem 25

Generate a random permutation of the elements of a list.

Example:

* (rnd-permu '(a b c d e f))
(B A D C E F)

Example in Haskell:

Prelude System.Random>rnd_permu "abcdef"
Prelude System.Random>"badcef"

Solution:

Using the nub solution from Problem 23 again,

rnd_permu xs = rnd_select xs (length xs)

With rnd_select as:

rnd_select :: [a] -> Int -> [a]
rnd_select x n = map (x!!) is
 where is = take n . nub $ randomRs (0, length x - 1) (mkStdGen 100)

Additional References:

Advertisements