# 99 questions/Solutions/25

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

Line 6: | Line 6: | ||

Uses the solution for the previous problem. Choosing N distinct elements from a list of length N will yield a permutation. | Uses the solution for the previous problem. Choosing N distinct elements from a list of length N will yield a permutation. | ||

+ | |||

+ | Or we can generate the permutation recursively: | ||

+ | |||

+ | <haskell> | ||

+ | import System.Random (randomRIO) | ||

+ | |||

+ | rnd_permu :: [a] -> IO [a] | ||

+ | rnd_permu [] = return [] | ||

+ | rnd_permu (x:xs) = do | ||

+ | rand <- randomRIO (0, (length xs)) | ||

+ | rest <- rnd_permu xs | ||

+ | return $ let (ys,zs) = splitAt rand rest | ||

+ | in ys++(x:zs) | ||

+ | </haskell> |

## Revision as of 06:24, 25 November 2010

Generate a random permutation of the elements of a list.

rnd_permu xs = diff_select' (length xs) xs

Uses the solution for the previous problem. Choosing N distinct elements from a list of length N will yield a permutation.

Or we can generate the permutation recursively:

import System.Random (randomRIO) rnd_permu :: [a] -> IO [a] rnd_permu [] = return [] rnd_permu (x:xs) = do rand <- randomRIO (0, (length xs)) rest <- rnd_permu xs return $ let (ys,zs) = splitAt rand rest in ys++(x:zs)