Shuffling Lists
Mark Elvers
~1 min read

Categories

  • ocaml

Tags

  • tunbury.org

Shuffling a list into a random order is usually handled by the Fisher-Yates Shuffle.

It could be efficiently written in OCaml using arrays:

Random.self_init ();

let fisher_yates_shuffle arr =
  let n = Array.length arr in
  for i = n - 1 downto 1 do
    let j = Random.int (i + 1) in
    let temp = arr.(i) in
    arr.(i) <- arr.(j);
    arr.(j) <- temp
  done

However, I had a one-off requirement to randomise a list, and this approach felt very functional.

Random.self_init ();

let shuffle lst =
  List.map (fun x -> (Random.bits (), x)) lst |> List.sort compare |> List.map snd