ocaml: phase 5.1 lcs.ml baseline (LCS of "ABCBDAB" and "BDCAB" = 4)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s

Classic 2D DP for longest common subsequence, optimized to use
two rolling 1D arrays (prev / curr) for O(min(m,n)) space:

  for i = 1 to m do
    for j = 1 to n do
      if s1.[i-1] = s2.[j-1] then curr.(j) <- prev.(j-1) + 1
      else if prev.(j) >= curr.(j-1) then curr.(j) <- prev.(j)
      else curr.(j) <- curr.(j-1)
    done;
    for j = 0 to n do prev.(j) <- curr.(j) done
  done;
  prev.(n)

  lcs "ABCBDAB" "BDCAB" = 4

Two valid LCS witnesses: BCAB and BDAB.

Avoids Array.make_matrix (not in our runtime) by manual rolling.

142 baseline programs total.
This commit is contained in:
2026-05-10 04:29:58 +00:00
parent 42a506faff
commit 7a67637826
3 changed files with 31 additions and 0 deletions

View File

@@ -82,6 +82,7 @@
"kadane.ml": 6,
"kmp.ml": 5,
"lambda_calc.ml": 7,
"lcs.ml": 4,
"majority_vote.ml": 4,
"levenshtein.ml": 11,
"memo_fib.ml": 75025,

23
lib/ocaml/baseline/lcs.ml Normal file
View File

@@ -0,0 +1,23 @@
let lcs 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 i = 1 to m do
for j = 1 to n do
if s1.[i - 1] = s2.[j - 1] then
curr.(j) <- prev.(j - 1) + 1
else if prev.(j) >= curr.(j - 1) then
curr.(j) <- prev.(j)
else
curr.(j) <- curr.(j - 1)
done;
for j = 0 to n do
prev.(j) <- curr.(j)
done
done;
prev.(n)
;;
lcs "ABCBDAB" "BDCAB"

View File

@@ -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-10 Phase 5.1 — lcs.ml baseline (longest common subsequence
of "ABCBDAB" and "BDCAB" = 4). Rolling-array DP in O(mn) time and
O(min(m,n)) space: keep `prev` and `curr` rows, copy after each
outer step. Two LCS witnesses: "BCAB" and "BDAB". Avoids needing
`Array.make_matrix` (not in our runtime) by manual rolling. Tests
string indexing, double-nested for-loops, sibling for to copy
rows, integer compare. 142 baseline programs total.
- 2026-05-10 Phase 5.1 — dijkstra.ml baseline (single-source shortest
path on a 5-node weighted graph, dist 0→4 = 7). O(n²) array-based
Dijkstra: at each step, scan unvisited vertices for the minimum