Files
rose-ash/lib/ocaml/baseline/next_permutation.ml
giles e057d9f18f
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
ocaml: phase 5.1 next_permutation.ml baseline (5! - 1 = 119 successors)
Standard in-place next-permutation (Narayana's algorithm):

  let next_perm a =
    let n = Array.length a in
    let i = ref (n - 2) in
    while !i >= 0 && a.(!i) >= a.(!i + 1) do i := !i - 1 done;
    if !i < 0 then false
    else begin
      let j = ref (n - 1) in
      while a.(!j) <= a.(!i) do j := !j - 1 done;
      swap a.(!i) a.(!j);
      reverse a (!i + 1) (n - 1);
      true
    end

Starting from [1;2;3;4;5], next_perm returns true 119 times then
false (when reverse-sorted). 5! - 1 = 119.

Tests guarded `while … && a.(!i) … do` loops that rely on the
iter-242 short-circuit fix.

156 baseline programs total.
2026-05-10 21:47:52 +00:00

31 lines
623 B
OCaml

let next_perm a =
let n = Array.length a in
let i = ref (n - 2) in
while !i >= 0 && a.(!i) >= a.(!i + 1) do
i := !i - 1
done;
if !i < 0 then false
else begin
let j = ref (n - 1) in
while a.(!j) <= a.(!i) do
j := !j - 1
done;
let t = a.(!i) in a.(!i) <- a.(!j); a.(!j) <- t;
let lo = ref (!i + 1) and hi = ref (n - 1) in
while !lo < !hi do
let t = a.(!lo) in a.(!lo) <- a.(!hi); a.(!hi) <- t;
lo := !lo + 1;
hi := !hi - 1
done;
true
end
;;
let a = [| 1; 2; 3; 4; 5 |] in
let count = ref 0 in
while next_perm a do
count := !count + 1
done;
!count