Files
rose-ash/lib/ocaml/baseline/shuffle.ml
giles 75a1adbbd5
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 48s
ocaml: phase 5.1 shuffle.ml baseline (Fisher-Yates with deterministic Random)
In-place Fisher-Yates shuffle using:

  Random.init 42                  deterministic seed
  let a = Array.of_list xs
  for i = n - 1 downto 1 do       reverse iteration
    let j = Random.int (i + 1)
    let tmp = a.(i) in
    a.(i) <- a.(j);
    a.(j) <- tmp
  done

Sum is invariant under permutation, so the test value (55 for
[1..10] = 1+2+...+10) verifies the shuffle is a valid permutation
regardless of which permutation the seed yields.

Exercises Random.init / Random.int + Array.of_list / to_list /
length / arr.(i) / arr.(i) <- v + downto loop + multi-statement
sequencing within for-body.

33 baseline programs total.
2026-05-09 07:31:33 +00:00

16 lines
300 B
OCaml

let shuffle xs =
Random.init 42;
let a = Array.of_list xs in
let n = Array.length a in
for i = n - 1 downto 1 do
let j = Random.int (i + 1) in
let tmp = a.(i) in
a.(i) <- a.(j);
a.(j) <- tmp
done;
Array.to_list a
;;
List.fold_left (+) 0 (shuffle [1;2;3;4;5;6;7;8;9;10])