ocaml: phase 5.1 shuffle.ml baseline (Fisher-Yates with deterministic Random)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 48s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 48s
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.
This commit is contained in:
@@ -29,6 +29,7 @@
|
||||
"quicksort.ml": 44,
|
||||
"roman.ml": 44,
|
||||
"safe_div.ml": 20,
|
||||
"shuffle.ml": 55,
|
||||
"sieve.ml": 15,
|
||||
"sum_squares.ml": 385,
|
||||
"unique_set.ml": 9,
|
||||
|
||||
15
lib/ocaml/baseline/shuffle.ml
Normal file
15
lib/ocaml/baseline/shuffle.ml
Normal file
@@ -0,0 +1,15 @@
|
||||
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])
|
||||
@@ -407,6 +407,13 @@ _Newest first._
|
||||
binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree *
|
||||
'a tree`) with insert + in-order traversal. Tests parametric ADT,
|
||||
recursive match, List.append, List.fold_left.
|
||||
- 2026-05-09 Phase 5.1 — shuffle.ml baseline (Fisher-Yates with
|
||||
deterministic Random.init seed). In-place swap loop using `for i =
|
||||
n - 1 downto 1` and `a.(i) <- a.(j)`. Sum is invariant under
|
||||
permutation, so the test value (55 for [1..10]) verifies that the
|
||||
shuffle is a valid permutation regardless of which one. Exercises
|
||||
Random.init / Random.int + Array.of_list / to_list / length /
|
||||
arr.(i) / arr.(i) <- v + downto loop. 33 baseline programs total.
|
||||
- 2026-05-09 Phase 5.1 — pi_leibniz.ml baseline (Leibniz formula,
|
||||
1000 terms × 100 → 314). Side-quest: `int_of_float` was wrong —
|
||||
defined as identity in iteration 94 instead of truncation. Fixed
|
||||
|
||||
Reference in New Issue
Block a user