Files
rose-ash/lib/ocaml/baseline/lev_iter.ml
giles b4571f0f9f
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
ocaml: phase 5.1 lev_iter.ml baseline (sum of 5 edit distances = 16)
Iterative Levenshtein DP with rolling 1D arrays for O(min(m,n))
space. Distances:

  kitten    -> sitting    : 3
  saturday  -> sunday     : 3
  abc       -> abc        : 0
  ""        -> abcde      : 5
  intention -> execution  : 5
  ----------------------------
  total                   : 16

Complementary to the existing levenshtein.ml which uses the
exponential recursive form (only sums tiny strings); this one is
the practical iterative variant used for real ED.

Tests the recently-fixed <- with bare `if` rhs:

  curr.(j) <- (if m1 < c then m1 else c) + 1

153 baseline programs total.
2026-05-10 06:53:38 +00:00

31 lines
761 B
OCaml

let lev_iter s1 s2 =
let m = String.length s1 in
let n = String.length s2 in
let prev = Array.make (n + 1) 0 in
let curr = Array.make (n + 1) 0 in
for j = 0 to n do prev.(j) <- j done;
for i = 1 to m do
curr.(0) <- i;
for j = 1 to n do
if s1.[i - 1] = s2.[j - 1] then
curr.(j) <- prev.(j - 1)
else begin
let a = prev.(j) in
let b = curr.(j - 1) in
let c = prev.(j - 1) in
let m1 = if a < b then a else b in
curr.(j) <- (if m1 < c then m1 else c) + 1
end
done;
for j = 0 to n do prev.(j) <- curr.(j) done
done;
prev.(n)
;;
lev_iter "kitten" "sitting"
+ lev_iter "saturday" "sunday"
+ lev_iter "abc" "abc"
+ lev_iter "" "abcde"
+ lev_iter "intention" "execution"