listrandomocamlelement

Generate a random permutation of the elements of a list OCaml


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"]

Solution

  • 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.