1

i whant generate a random permutation of elements of a list, Example:

listString =  ["a"; "b"; "c"; "d"; "e"; "f"]

i whant something like:

result = ["a"; "e"; "f"; "b"; "d"; "c"]

but that result change in each call of the function. So when i call the function in second time return something like:

result = ["c"; "d"; "b"; "f"; "e"; "a"]
NahuelBrandan
  • 633
  • 6
  • 16
  • Possible duplicate of [How to shuffle list in O(n) in OCaml?](http://stackoverflow.com/questions/15095541/how-to-shuffle-list-in-on-in-ocaml) – hugomg Aug 07 '16 at 23:42
  • thats i seeing, but that function repeat the same permutation in every call of that function. I try generate a random int 'n' and use that function shuffle n times. – NahuelBrandan Aug 08 '16 at 00:28
  • Now Random.int do the same number every times :/ – NahuelBrandan Aug 08 '16 at 00:31

1 Answers1

1

i found the solution:

 let shuffle d = begin
    Random.self_init ();
    let nd = List.map (fun c -> (Random.bits (), c)) d in
    let sond = List.sort compare nd in
    List.map snd sond
 end

the line Random.self_init (); Initialize the generator with a random seed chosen in a system-dependent way.

NahuelBrandan
  • 633
  • 6
  • 16
  • You probably want to initialize the RNG only once, at the start of your program (and outside of the shuffle function). – hugomg Aug 08 '16 at 02:25