Commit Graph

2747 Commits

Author SHA1 Message Date
33be068c01 ocaml: phase 5.1 min_subarr_target.ml baseline (min subarray sum >= 7 = 2)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Classic two-pointer / sliding window: expand right, then shrink
left while the window still satisfies the >= constraint, recording
the smallest valid length.

  for r = 0 to n - 1 do
    sum := !sum + arr.(r);
    while !sum >= target do
      ... record (r - !l + 1) if smaller ...
      sum := !sum - arr.(!l);
      l := !l + 1
    done
  done

For [2; 3; 1; 2; 4; 3], target 7 -> window [4, 3] of length 2.

Sentinel n+1 marks "not found"; final guard reduces to 0.

Tests for + inner while shrinking loop, ref-tracked sum updated
on both expansion and contraction.

194 baseline programs total.
2026-05-11 04:24:29 +00:00
bf468e5ec3 ocaml: phase 5.1 min_meeting_rooms.ml baseline (8 meetings, min 4 rooms)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Sweep-line algorithm via separately-sorted starts / ends arrays:

  while i < n do
    if starts[i] < ends[j] then begin busy++; rooms = max; i++ end
    else begin busy--; j++ end
  done

  intervals: (0,30) (5,10) (15,20) (10,25) (5,12)
             (20,35) (0,5)  (8,18)

At time 8, meetings (0,30), (5,10), (5,12), (8,18) are all active
simultaneously -> answer = 4.

Tests local helper bound via let (`let bubble a = ...`) for
in-place sort, dual-pointer sweep on parallel ordered event streams.

193 baseline programs total.
2026-05-11 04:14:33 +00:00
90ba37ecc8 ocaml: phase 5.1 activity_select.ml baseline (greedy non-overlap = 4)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Activity selection by earliest end time. Manual bubble sort over
(start, end) tuple array, then sweep accepting whenever the next
start >= last_end.

  intervals: (1,4) (3,5) (0,6) (5,7) (3,8) (5,9) (6,10) (8,11)
             (8,12) (2,13) (12,14)

  selection: (1,4) -> (5,7) -> (8,11) -> (12,14)  = 4 activities

Tests double-loop bubble sort on tuple array with let-pattern
destructure for swap-key extraction, in-place swap of tuple cells.

192 baseline programs total.
2026-05-11 04:04:42 +00:00
3f00e62577 ocaml: phase 5.1 count_paths_dag.ml baseline (source-to-sink paths = 3)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Count source-to-sink paths in a DAG via Kahn's topological sort
plus accumulation:

  paths[source] = 1
  for u in topological order:
    for v in adj[u]: paths[v] += paths[u]

Same 6-node DAG as topo_sort.ml:
  0 -> {1, 2}    1 -> {3}    2 -> {3, 4}    3 -> {5}    4 -> {5}

The three witnesses 0 -> 5:
  0 -> 1 -> 3 -> 5
  0 -> 2 -> 3 -> 5
  0 -> 2 -> 4 -> 5

Tests Queue-driven Kahn order + List.rev to recover topological
order, module-level mutable arrays (in_deg, paths), accumulation
in topological traversal.

191 baseline programs total.
2026-05-11 03:54:52 +00:00
97a29c6bac ocaml: phase 5.1 stock_two.ml baseline (best of 2 transactions = 6)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Two-pass partition DP for max profit with at most 2 transactions:

  left[i]  = max single-trans profit in prices[0..i]
              (forward scan tracking running min)
  right[i] = max single-trans profit in prices[i..n-1]
              (backward scan tracking running max)
  answer   = max over i of (left[i] + right[i])

For [3; 3; 5; 0; 0; 3; 1; 4]:
  optimal partition i = 2:
    left[2]  = sell@5 after buy@3            = 2
    right[2] = sell@4 after buy@0 in [2..7]  = 4
                                       total = 6

Tests parallel forward + backward passes on parallel DP arrays,
mixed ref + array state, for downto + for ascending scans on
the same data.

190 baseline programs total.
2026-05-11 03:44:40 +00:00
73efd229be ocaml: phase 5.1 house_robber.ml baseline (max non-adjacent sum = 22)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Classic House Robber linear DP:

  dp[i] = max(dp[i-2] + houses[i], dp[i-1])

For [2; 7; 9; 3; 1; 5; 8; 6]:

  dp = [2, 7, 11, 11, 12, 16, 20, 22]
  max sum = 22

Optimal pick is {indices 0, 2, 5, 7}: 2 + 9 + 5 + 6 = 22 (all
non-adjacent).

Tests linear DP with early-return edge cases for n=0 and n=1,
inline-if rhs for max-of-two, dual look-back into dp[i-2] and
dp[i-1].

189 baseline programs total.
2026-05-11 03:34:48 +00:00
6d89da9380 ocaml: phase 5.1 interval_overlap.ml baseline (7 intervals, 6 overlapping pairs)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
For each (i, j) pair with i < j, test whether intervals (s1, e1)
and (s2, e2) overlap via the standard `s1 <= e2 && s2 <= e1`.

  intervals: (1,4) (2,5) (7,9) (3,6) (8,10) (11,12) (0,2)

  overlapping pairs:
    (1,4) & (2,5)        (1,4) & (3,6)        (1,4) & (0,2)
    (2,5) & (3,6)        (2,5) & (0,2)
    (7,9) & (8,10)
                                                     = 6

Tests double for-loop with both-side tuple destructure via
`let (s1, e1) = arr.(i) in`, conjunctive comparison, list-to-
array conversion.

188 baseline programs total.
2026-05-11 03:24:45 +00:00
d3340107e6 ocaml: phase 5.1 count_palindromes.ml baseline ("aabaa" -> 9 palindromes)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Expand-around-center linear-time palindrome counting:

  for c = 0 to 2*n - 2 do
    let l = ref (c / 2) in
    let r = ref ((c + 1) / 2) in
    while !l >= 0 && !r < n && s.[!l] = s.[!r] do
      count := !count + 1; l := !l - 1; r := !r + 1
    done
  done

The 2n-1 centers cover both odd (c even -> l = r) and even
(c odd -> l = r - 1) palindromes.

For "aabaa":
  5 singletons + 2 "aa" + 1 "aba" + 1 "aabaa" = 9

Complements lps_dp.ml (longest subsequence) and manacher.ml
(longest substring); this one *counts* all palindromic substrings.

187 baseline programs total.
2026-05-11 03:14:23 +00:00
aaa6020037 ocaml: phase 5.1 count_subarrays_k.ml baseline (sum-k subarrays = 7)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Count contiguous subarrays summing to a target k using a prefix
sum table:

  prefix[i+1] = prefix[i] + arr[i]
  count = |{ (i, j) : 0 <= i < j <= n,  prefix[j] - prefix[i] = k }|

For arr = [1; 1; 1; 2; -1; 3; 1; -2; 4] and k = 3, the seven
witnesses are:

  [1, 1, 1]            (0..2)
  [1, 1, 2, -1]        (1..4)
  [1, 2]               (2..3)
  [2, -1, 3, 1, -2]    (3..7)
  [-1, 3, 1]           (4..6)
  [3]                  (5..5)
  [1, -2, 4]           (6..8)

Negative-valued arrays exercise mixed-sign integer arithmetic.

186 baseline programs total.
2026-05-11 03:04:14 +00:00
8ef24847d3 ocaml: phase 5.1 floyd_cycle.ml baseline (tortoise-hare, mu=0 lam=8 -> 8)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Floyd's cycle detection on a numeric function f(x) = (2x + 5) mod 17.
Three phases:

  Phase 1: advance slow/fast until collision inside the cycle
            (fast double-steps, slow single-steps)
  Phase 2: restart slow from x0; advance both by 1 until they
            meet — count is mu (length of tail before cycle)
  Phase 3: advance fast around cycle once until it meets slow
            — count is lam (cycle length)

For x0 = 1, the orbit visits 1, 7, 2, 9, 6, 0, 5, 15 then returns
to 1 — pure cycle of length 8, mu = 0, lam = 8. Encoded as
mu*100 + lam = 8.

Tests three sequential while loops sharing ref state,
double-step `fast := f (f !fast)`, meeting-condition flag.

185 baseline programs total.
2026-05-11 02:54:50 +00:00
b3ee88e9bb ocaml: phase 5.1 kth_two.ml baseline (8th smallest of two sorted = 8)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Two-pointer merge advancing the smaller-head pointer k times,
without materializing the merged array:

  while !count < k do
    let pick_a =
      if !i = m then false        (* a exhausted, take from b *)
      else if !j = n then true    (* b exhausted, take from a *)
      else a.(!i) <= b.(!j)
    in
    if pick_a then ... else ...;
    count := !count + 1
  done

For a = [1;3;5;7;9;11;13], b = [2;4;6;8;10;12]:
  merged order: 1,2,3,4,5,6,7,8,9,10,11,12,13
  8th element = 8.

Tests nested if/else if/else flowing into a bool, dual-ref
two-pointer loop, separate count counter for k-th constraint.

184 baseline programs total.
2026-05-11 02:44:40 +00:00
2c7a1bfc47 ocaml: phase 5.1 permutations_gen.ml baseline (24 perms, 12 with a<b ends)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Recursive permutation generator via fold-pick-recurse:

  let rec permutations xs = match xs with
    | [] -> [[]]
    | _ ->
      List.fold_left (fun acc x ->
        let rest = List.filter (fun y -> y <> x) xs in
        let subs = permutations rest in
        acc @ List.map (fun p -> x :: p) subs
      ) [] xs

For permutations of [1; 2; 3; 4] (24 total), count those whose
first element is less than the last:

  match p with
  | [a; _; _; b] when a < b -> count := !count + 1
  | _ -> ()

By symmetry, exactly half satisfy a < b = 12.

Tests List.filter, recursive fold with append, fixed-length
list pattern [a; _; _; b] with multiple wildcards + when guard.

183 baseline programs total.
2026-05-11 02:34:58 +00:00
047ea62d43 ocaml: phase 5.1 regex_simple.ml baseline (./* matcher, 7/28 match)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Recursive regex matcher with Leetcode-style semantics:
  .   matches any single character
  <c>* matches zero or more of <c>

  let rec is_match s i p j =
    if j = String.length p then i = String.length s
    else
      let first = i < String.length s
                  && (p.[j] = '.' || p.[j] = s.[i])
      in
      if j + 1 < String.length p && p.[j+1] = '*' then
           is_match s i p (j + 2)                   (* skip * group *)
        || (first && is_match s (i + 1) p j)        (* consume one  *)
      else
        first && is_match s (i + 1) p (j + 1)

Patterns vs texts:
  .a.b    | aabb axb "" abcd abc aaabbbc x   -> 1 match
  a.*b    | aabb axb "" abcd abc aaabbbc x   -> 2 matches
  x*      | aabb axb "" abcd abc aaabbbc x   -> 2 matches
  a*b*c   | aabb axb "" abcd abc aaabbbc x   -> 2 matches
                                             total = 7

Complements wildcard_match.ml which uses LIKE-style * / ?.

182 baseline programs total.
2026-05-11 02:25:04 +00:00
2726ed9b8a ocaml: phase 5.1 palindrome_part.ml baseline (min cuts "aabba" = 1)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Two-phase palindrome-partition DP for the minimum-cuts variant:

  Phase 1: is_pal[i][j] palindrome table via length-major fill
           (single chars, then pairs, then expand inward).

  Phase 2: cuts[i] = 0 if s[0..i] is itself a palindrome,
                  = min over j of (cuts[j-1] + 1)
                    where s[j..i] is a palindrome.

  min_cut "aabba" = 1   ("a" | "abba")

Tests two sequential 2D DPs sharing the same is_pal matrix,
inline begin/end branches inside the length-major fill, mixed
bool and int 2D arrays.

181 baseline programs total.
2026-05-11 02:14:44 +00:00
6d7df11224 ocaml: phase 5.1 island_count.ml baseline (6x7 grid, 5 components)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Count 4-connected components of 1-cells via DFS flood from every
unvisited 1-cell.

Grid (1s shown as #):
  # # . . . # #
  # . . . # # .
  . . # # . . .
  . # # # . # #
  # . . . . # .
  # # . # # # .

Components:
  {(0,0),(0,1),(1,0)}
  {(0,5),(0,6),(1,4),(1,5)}
  {(2,2),(2,3),(3,1),(3,2),(3,3)}
  {(3,5),(3,6),(4,5),(5,3),(5,4),(5,5)}
  {(4,0),(5,0),(5,1)}
                              -> 5 islands

Complementary to flood_fill.ml (largest component); this counts
total components.

Tests recursive function returning () at early-exit branches,
ordered double-for entry pass triggering one fill per island root.

180 baseline programs total.
2026-05-11 02:04:08 +00:00
8a80bd3923 ocaml: phase 5.1 dp_word_break.ml baseline (4/5 strings segmentable)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Classic word-break DP — for each position i, check whether any
dictionary word ends at i with a prior reachable position:

  dp[i] = exists w in dict with wl <= i and
          dp[i - wl] && s.sub (i - wl) wl = w

Dictionary: apple, pen, pine, pineapple, cats, cat, and, sand, dog
Inputs:
  applepenapple        yes  (apple pen apple)
  pineapplepenapple    yes  (pineapple pen apple)
  catsanddog           yes  (cats and dog)
  catsandog            no   (no segmentation reaches the end)
  applesand            yes  (apple sand)

Tests bool-typed Array, String.sub primitive, nested List.iter
over the dict inside for-loop over end positions, closure capture
of the outer dp.

179 baseline programs total.
2026-05-11 01:53:21 +00:00
609205b551 ocaml: phase 5.1 histogram_area.ml baseline (largest rectangle = 10)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Linear-time stack algorithm for largest rectangle in histogram:

  for i = 0 to n do
    let h = if i = n then 0 else heights.(i) in
    while top-of-stack's height > h do
      pop the top, compute its max-width rectangle:
        width = (no-stack ? i : i - prev_top - 1)
        area  = height * width
      update best
    done;
    if i < n then push i
  done

Sentinel pass at i=n with h=0 flushes the remaining stack.

For [2; 1; 5; 6; 2; 3], bars at indices 2 (h=5) and 3 (h=6) form
a width-2 rectangle of height 5 = 10.

Tests guarded patterns with `when` inside while-cont-flag, nested
`match !stack with | [] -> i | t :: _ -> i - t - 1` for width
computation.

178 baseline programs total.
2026-05-11 01:42:26 +00:00
f9371e7d22 ocaml: phase 5.1 lps_dp.ml baseline (LPS "BBABCBCAB" = 7)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Standard O(n^2) length-major DP for longest palindromic
subsequence:

  dp[i][j] = dp[i+1][j-1] + 2                if s[i] = s[j]
           = max(dp[i+1][j], dp[i][j-1])     otherwise

  lps "BBABCBCAB" = 7   (witness "BABCBAB" etc.)

Complementary to manacher.ml (longest palindromic *substring*,
also length 7 on that input by coincidence) — this is the
subsequence variant which doesn't require contiguity.

Tests length-major fill order, inline if for the length-2 base
case, double-nested for with derived j = i + len - 1.

177 baseline programs total.
2026-05-11 01:32:41 +00:00
7f310a4da7 ocaml: phase 5.1 bs_bounds.ml baseline (lower/upper bound, fingerprint 3211)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
C++-style lower_bound / upper_bound on a sorted array:

  lower_bound — first index >= x  (loop uses arr.(mid) < x)
  upper_bound — first index >  x  (loop uses arr.(mid) <= x)

  a = [|1; 2; 2; 3; 3; 3; 5; 7; 9|]

  upper(x) - lower(x) gives the count of x in a:
    cnt3 = 3   cnt2 = 2   cnt5 = 1   cnt9 = 1   cnt4 = 0

  fingerprint = 3*1000 + 2*100 + 1*10 + 1 + 0 = 3211

Tests parallel while loops with bisection on ref, mixed strict
and non-strict comparison branches, count-via-subtraction idiom.

176 baseline programs total.
2026-05-11 01:22:31 +00:00
6780acd0af ocaml: phase 5.1 distinct_subseq.ml baseline ("rabbit" in "rabbbit" = 3)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Classic distinct-subsequences 2D DP:

  dp[i][j] = dp[i-1][j] + (s[i-1] = t[j-1] ? dp[i-1][j-1] : 0)
  dp[i][0] = 1   (empty t is a subseq of any prefix of s)

  count_subseq "rabbbit" "rabbit" = 3

The three witnesses correspond to which 'b' in "rabbbit" is
dropped (positions 2, 3, or 4 zero-indexed of the run of bs).

Complements subseq_check.ml (just tests presence); this one counts
distinct embeddings.

Tests 2D DP with Array.init n (fun _ -> Array.make m 0), base row
initialization, mixed string + array indexing.

175 baseline programs total.
2026-05-11 01:12:33 +00:00
b771ea306c ocaml: phase 5.1 bracket_match.ml baseline (5/9 balanced strings)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Stack-based multi-bracket parenthesis matching for ( [ { ) ] }.
Non-bracket chars are skipped (treated as content).

Tests:
  ()           yes
  [{()}]       yes
  ({[}])       no  (mismatched closer)
  ""           yes
  ((           no  (unclosed)
  ()[](){}     yes
  (a(b)c)      yes  (a/b/c skipped)
  (()          no
  ])           no
                 5 balanced

Body uses begin/end-wrapped match inside while:

  else if c = ')' || c = ']' || c = '}' then begin
    match !stack with
    | [] -> ok := false
    | top :: rest ->
      let pair =
        (c = ')' && top = '(') ||
        (c = ']' && top = '[') ||
        (c = '}' && top = '{')
      in
      if pair then stack := rest else ok := false
  end

Tests side-effecting match arms inside while body, ref-of-list as
stack, multi-char pairing dispatch.

174 baseline programs total.
2026-05-11 01:02:59 +00:00
6c77dec495 ocaml: phase 5.1 wildcard_match.ml baseline (* / ? matcher, 6/18 match)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Recursive wildcard matcher:

  let rec is_match s i p j =
    if j = String.length p then i = String.length s
    else if p.[j] = '*' then
         is_match s i p (j + 1)             (* * matches empty   *)
      || (i < String.length s && is_match s (i + 1) p j)  (* * eats char *)
    else
      i < String.length s
      && (p.[j] = '?' || p.[j] = s.[i])
      && is_match s (i + 1) p (j + 1)

Patterns vs texts:
  a*b      | aaab abc abxyz xy xyz axby   -> 1 match
  ?b*c     | aaab abc abxyz xy xyz axby   -> 1 match
  *x*y*    | aaab abc abxyz xy xyz axby   -> 4 matches
                                  total   = 6

Tests deeply nested short-circuit && / ||, char equality on
pattern bytes, doubly-nested List.iter cross product.

173 baseline programs total.
2026-05-11 00:52:42 +00:00
0a3f02d636 ocaml: phase 5.1 powerset_target.ml baseline (subsets of {1..10} summing to 15 = 20)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Recursive powerset construction by doubling:

  let rec gen xs = match xs with
    | [] -> [[]]
    | h :: rest ->
      let sub = gen rest in
      sub @ List.map (fun s -> h :: s) sub

Enumerates all 2^10 = 1024 subsets, filters by sum:

  count = |{ S ⊆ {1..10} | Σ S = 15 }| = 20

Examples: {1,2,3,4,5}, {2,3,4,6}, {1,4,10}, {7,8}, {6,9}, ...

Tests recursive subset construction via List.map + closures,
pattern matching with h :: rest, List.fold_left (+) 0 sum reduce,
exhaustive O(2^n * n) traversal.

172 baseline programs total.
2026-05-11 00:42:08 +00:00
800dca67ca ocaml: parser accepts top-level tuple patterns in match cases
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Real OCaml accepts `match e1, e2 with | p1, p2 -> …` without
surrounding parens. parse-pattern previously stopped at the cons
layer (`p :: rest`) and treated a trailing `,` as a separator
the outer caller couldn't handle, surfacing as
"expected op -> got op ,".

Fix: `parse-pattern` now collects comma-separated patterns into a
:ptuple after parse-pattern-cons, before the optional `as` alias.
The scrutinee side already built tuples via parse-tuple, so both
sides are now symmetric.

lru_cache.ml (iter 258) reverts its workaround back to the natural
form:

  let rec take n lst = match n, lst with
    | 0, _ -> []
    | _, [] -> []
    | _, h :: r -> h :: take (n - 1) r

607/607 regressions clean.
2026-05-11 00:31:08 +00:00
fd1f94f292 ocaml: phase 5.1 lru_cache.ml baseline (cap=3 LRU, fingerprint 499)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Functional LRU cache via association-list ordered most-recent-first.
Get / put both:
  - find or remove the existing entry
  - cons the fresh (k, v) to the front
  - on put, trim the tail when over capacity

Sequence:
  put 1 100; put 2 200; put 3 300
  a = get 1  -> 100  (moves 1 to front)
  put 4 400          (evicts 2)
  b = get 2  -> -1   (no longer cached)
  c = get 3  -> 300
  d = get 1  -> 100
  a + b + c + d = 499

Tests `match … with (k', v) :: rest when k' = k -> …` tuple-cons
patterns with `when` guards, `function` keyword for arg-less
match, recursive find/remove/take over the same list.

Parser limit found: `match n, lst with` ad-hoc tuple-scrutinee is
not yet supported (got "expected op -> got op ,"); workaround
uses outer `if` plus inner match.

171 baseline programs total.
2026-05-11 00:20:30 +00:00
1d1c35a438 ocaml: phase 5.1 convex_hull.ml baseline (Andrew monotone chain, 5 vertices)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Andrew's monotone chain hull over 8 integer points:

  pts = [(0,0); (1,1); (2,0); (2,2); (0,2); (1,0); (3,3); (5,1)]

Sort lex, build lower hull L->R then upper R->L, popping while
the cross product is non-positive (collinear included on hull).

Hull traverse: (0,0) -> (2,0) -> (5,1) -> (3,3) -> (0,2) = 5
((2,0) lies on the lower edge from (0,0) to (5,1)).

Tests List.sort with 2-tuple comparator using nested pair
destructure, repeated `let (x, y) = arr.(i) in` array tuple
destructure across both passes, while + cont-flag pattern.

170 baseline programs total.
2026-05-11 00:09:06 +00:00
ca34cede88 ocaml: phase 5.1 next_greater.ml baseline (monotonic stack, sum 153)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Right-to-left monotonic stack for next-greater-element:

  for i = n - 1 downto 0 do
    while (match !stack with [] -> false | h :: _ -> h <= arr.(i)) do
      stack := List.tl !stack
    done;
    (match !stack with
     | [] -> res.(i) <- -1
     | h :: _ -> res.(i) <- h);
    stack := arr.(i) :: !stack
  done

For [4; 5; 2; 25; 7; 8; 1; 30; 12]:
  results: [5; 25; 25; 30; 8; 30; 30; -1; -1]
  sum of non-negative = 5+25+25+30+8+30+30 = 153

Tests stack as ref list with match-driven peek, match-as-bool in
while-guard, inline parenthesized match driving <-.

169 baseline programs total.
2026-05-10 23:58:50 +00:00
cb626fc402 ocaml: phase 5.1 fenwick_tree.ml baseline (BIT over 8 elements, fingerprint 228)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Fenwick / Binary Indexed Tree for prefix sums. The classic
`i & -i` low-bit trick needs negative-aware AND, but our `land`
evaluator (iter 127, bitwise via floor/mod arithmetic) only handles
non-negative operands. Workaround: a portable lowbit helper that
finds the largest power of 2 dividing i:

  let lowbit i =
    let r = ref 1 in
    while !r * 2 <= i && i mod (!r * 2) = 0 do
      r := !r * 2
    done;
    !r

After building from [1;3;5;7;9;11;13;15]:
  total       = prefix_sum 8 = 64
  update 1 by +100
  after       = prefix_sum 8 = 164
  total + after = 228

Tests recursive update / prefix_sum chains via helper-extracted
lowbit; documents a non-obvious limit of the bitwise-emulation
layer.

168 baseline programs total.
2026-05-10 23:48:46 +00:00
175a77fba5 ocaml: phase 5.1 segment_tree.ml baseline (range-sum tree, fingerprint 4232)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Power-of-two-indexed segment tree over [1;3;5;7;9;11;13;15]:
  build sums (root holds total = 64)
  query returns range sum in O(log n)
  update propagates a point delta back up the path

Sequence:
  r1 = query [2,5] = 5 + 7 + 9 + 11 = 32
  update idx 3 += 10  (so a[3] becomes 17)
  r2 = query [2,5] = 5 + 17 + 9 + 11 = 42
  encoded fingerprint = r1 + r2*100 = 32 + 4200 = 4232

Tests three mutually independent recursive functions with array
index arithmetic on 2*node / 2*node+1, half-bisection on mid =
(l+r)/2, bottom-up combine pattern.

167 baseline programs total.
2026-05-10 23:38:40 +00:00
3fe3b7b66f ocaml: phase 5.1 magic_square.ml baseline (5x5 Siamese, diag sum = 65)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Siamese construction for odd-order magic squares:

  - place 1 at (0, n/2)
  - for k = 2..n^2, move up-right with (x-1+n) mod n wrap
  - if the target cell is taken, drop down one row instead

  for n=5, magic constant = n*(n^2+1)/2 = 5*26/2 = 65

Returns the main-diagonal sum (65 by construction).

Tests 2D array via Array.init + Array.make, mod arithmetic with
the (x-1+n) mod n idiom for negative-safe wrap, nested begin/end
branches inside for-loop body.

166 baseline programs total.
2026-05-10 23:28:29 +00:00
689438d12e ocaml: phase 5.1 matrix_power.ml baseline (F(30) = 832040 via 2x2 matrix pow)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Fibonacci via repeated-squaring matrix exponentiation:

  [[1, 1], [1, 0]] ^ n = [[F(n+1), F(n)], [F(n), F(n-1)]]

Recursive O(log n) power:

  let rec mpow m n =
    if n = 0 then identity
    else if n mod 2 = 0 then let h = mpow m (n / 2) in mul h h
    else mul m (mpow m (n - 1))

Returns the .b cell after raising to the 30th power -> 832040 = F(30).

Tests record literal construction inside recursive function returns,
record field access (x.a etc), and pure integer arithmetic in the
matrix multiply.

165 baseline programs total.
2026-05-10 23:18:26 +00:00
d1a4616ac4 ocaml: phase 5.1 bipartite.ml baseline (7-node bipartite, 4 in color 0)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
BFS-based 2-coloring of an undirected graph:

  edges (undirected):
    0-1  0-3  1-2  1-4  2-5  3-4  3-6  5-6

  Partition: {0, 2, 4, 6} vs {1, 3, 5} (no odd cycles)

Returns count of color-0 vertices (4) on success, -1 on odd-cycle
detection.

Tests Queue-based BFS with a source-loop wrapper for disconnected
graphs, `1 - color.(u)` toggle, color-equality conflict check
on already-colored neighbors.

164 baseline programs total.
2026-05-10 23:08:16 +00:00
32f6c4ee0c ocaml: phase 5.1 egg_drop.ml baseline (2 eggs, 36 floors -> 8 trials)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Classic egg-drop puzzle DP:

  dp[e][f] = 1 + min over k in [1, f] of
              max(dp[e-1][k-1], dp[e][f-k])

For 2 eggs over 36 floors, the optimal worst-case is 8 trials
(closed form: triangular number bound).

Tests 2D DP with triple-nested for-loops, max-of-two via inline
if, large sentinel constant (100000000), mixed shifted indexing
(e-1) and (f-k) where both shift independently.

163 baseline programs total.
2026-05-10 22:58:13 +00:00
62712accdd ocaml: phase 5.1 polygon_area.ml baseline (pentagon 2x area = 32)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Shoelace formula on a pentagon with integer vertices:

  pts = [(0,0); (4,0); (4,3); (2,5); (0,3)]

  2 * area = | Σ (x_i * y_{i+1} - x_{i+1} * y_i) |
           = | 0*0 - 4*0 + 4*3 - 4*0 + 4*5 - 2*3 + 2*3 - 0*5
                + 0*0 - 0*3 |
           = 32

Returns the doubled form (32) to stay integral.

Tests:
  - let (x1, y1) = arr.(i) in   -- tuple destructure from array
  - arr.((i + 1) mod n)         -- modular wrap-around index
  - if a < 0 then - a else a    -- prefix - negation

162 baseline programs total.
2026-05-10 22:47:22 +00:00
c69a7694c8 ocaml: phase 5.1 min_cost_path.ml baseline (4x4 grid DP, optimal cost 12)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Standard 2D DP for min-cost path with right/down moves only:

  dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + cost[i][j]

  cost:                  dp:
    1 3 1 2                1  4  5  7
    1 5 1 3                2  7  6  9
    4 2 1 4                6  8  7 11
    1 6 2 3                7 13  9 12

Optimal cost from (0,0) to (3,3) = 12.

Tests nested 2D arrays via Array.init + Array.make, double-nested
for-loops with branched edges (first row, first column, general),
mixed .(i-1).(j) read + .(i).(j)<- write on the same DP array.

161 baseline programs total.
2026-05-10 22:37:44 +00:00
5384ff6c42 ocaml: phase 5.1 topo_dfs.ml baseline (DFS topo sort, fingerprint 24135)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
DFS topological sort — recurse on out-edges first, prepend after:

  let rec dfs v =
    if not visited.(v) then begin
      visited.(v) <- true;
      List.iter dfs adj.(v);
      order := v :: !order
    end

Same 6-node DAG as iter 230's Kahn's-algorithm baseline:
  0 -> {1, 2}
  1 -> {3}
  2 -> {3, 4}
  3 -> {5}
  4 -> {5}
  5

DFS order: [0; 2; 4; 1; 3; 5]
Horner fold: 0->0->2->24->241->2413->24135.

Complementary to topo_sort.ml (Kahn's BFS); tests recursive DFS
with no explicit stack + List.fold_left as a horner reduction.

160 baseline programs total.
2026-05-10 22:27:18 +00:00
bcb7db2ea4 ocaml: phase 5.1 radix_sort.ml baseline (LSD radix sort, sentinel 802002)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
LSD radix sort over base 10 digits. Per pass:
  - 10 bucket-refs created via Array.init 10 (fun _ -> ref []) (each
    closure call yields a distinct list cell)
  - scan array, append each value to its digit's bucket
  - flatten buckets back to the array in order

Input  [170;45;75;90;802;24;2;66]
Output [2;24;45;66;75;90;170;802]

Sentinel: a.(0) + a.(7)*1000 = 2 + 802*1000 = 802002.

Tests array-of-refs with !buckets.(d) deref, list-mode bucket
sort within in-place array sort, unused for-loop var (`for _ =
1 to maxd`).

159 baseline programs total.
2026-05-10 22:17:40 +00:00
5eed0dd5f5 ocaml: phase 5.1 coin_min.ml baseline (67 cents in US coins = 6)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Minimum-coin DP with -1 sentinel for unreachable values:

  let coin_min coins amount =
    let dp = Array.make (amount + 1) (-1) in
    dp.(0) <- 0;
    for i = 1 to amount do
      List.iter (fun c ->
        if c <= i && dp.(i - c) >= 0 then begin
          let cand = dp.(i - c) + 1 in
          if dp.(i) < 0 || cand < dp.(i) then dp.(i) <- cand
        end
      ) coins
    done;
    dp.(amount)

  coin_min [1; 5; 10; 25] 67 = 6   (* 25+25+10+5+1+1 *)

Tests `if c <= i && dp.(i-c) >= 0 then` short-circuit guard;
relies on iter-242 fix so dp.(i-c) is not evaluated when c > i.

158 baseline programs total.
2026-05-10 22:07:17 +00:00
3ea8967571 ocaml: phase 5.1 flood_fill.ml baseline (largest grid component = 7)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Recursive 4-way flood fill from every unvisited 1-cell:

  let rec flood visited r c =
    if r < 0 || r >= h || c < 0 || c >= w then 0
    else if visited.(r).(c) || grid.(r).(c) = 0 then 0
    else begin
      visited.(r).(c) <- true;
      1 + flood visited (r - 1) c
        + flood visited (r + 1) c
        + flood visited r (c - 1)
        + flood visited r (c + 1)
    end

Grid (1s shown as #, 0s as .):
  # # . # #
  # . . . #
  . . # . .
  # # # # .
  . . . # #

Largest component: {(2,2),(3,0),(3,1),(3,2),(3,3),(4,3),(4,4)} = 7.

Bounds check r >= 0 must short-circuit before visited/grid reads;
relies on the && / || fix from iter 242.

157 baseline programs total.
2026-05-10 21:57:42 +00:00
e057d9f18f ocaml: phase 5.1 next_permutation.ml baseline (5! - 1 = 119 successors)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
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
4761d41a0d ocaml: && / || short-circuit fix + bfs_grid.ml baseline (5x5 grid, dist 8)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Before: `:op` handler always evaluated both operands before dispatching
to ocaml-eval-op. For pure binops that's fine, but `&&` / `||` MUST
short-circuit:

  if nr >= 0 && grid.(nr).(nc) = 0 then ...

When nr = -1, real OCaml never evaluates `grid.(-1)`. Our evaluator
did, and crashed with "nth: list/string and number".

Fix: special-case `&&` and `||` in :op dispatch, mirroring the same
pattern already used for `:=` and `<-`. Evaluate lhs, branch on it,
and only evaluate rhs when needed.

Latent since baseline 1 — earlier programs never triggered it because
the rhs was unconditionally safe.

bfs_grid.ml: shortest path through a 5x5 grid with walls. Standard
BFS using Queue.{push,pop,is_empty} + Array.init for the 2D distance
matrix. Path 0,0 -> ... -> 4,4 has length 8. 155 baseline programs
total.
2026-05-10 21:37:41 +00:00
bed374c9e1 ocaml: phase 5.1 tarjan_scc.ml baseline (8-node digraph, 4 SCCs)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Tarjan's strongly-connected components in a single DFS using
index/lowlink:

  graph (8 nodes, directed):
    0 -> 1 -> 2 -> 0   (3-cycle)
    2 -> 3
    3 -> 4
    4 -> 5 -> 6 -> 4   (3-cycle)
    4 -> 7

  SCCs: {0,1,2}, {3}, {4,5,6}, {7}  =  4 components

Module-level ref + array state (index_arr, lowlink, on_stack,
stack, scc_count). When lowlink(v) = index(v), pop from stack
until v is removed; that's a complete SCC.

Tests: recursive function with module-level mutable state,
nested begin/end branches inside List.iter closure, inner
`let rec pop ()` traversing a ref-of-list, pattern match on
[] / h :: rest cons-list shape.

154 baseline programs total.
2026-05-10 07:06:29 +00:00
b4571f0f9f ocaml: phase 5.1 lev_iter.ml baseline (sum of 5 edit distances = 16)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
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
0ef26b20f3 ocaml: phase 5.1 binary_heap.ml baseline (min-heap sort 9 vals -> 123456789)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Array-backed binary min-heap with explicit size tracking via ref:

  let push a size x =
    a.(!size) <- x; size := !size + 1; sift_up a (!size - 1)

  let pop a size =
    let m = a.(0) in
    size := !size - 1;
    a.(0) <- a.(!size);
    sift_down a !size 0;
    m

Push [9;4;7;1;8;3;5;2;6], pop nine times -> 1,2,3,4,5,6,7,8,9.
Fold-as-decimal: ((((((((1*10+2)*10+3)*10+4)*10+5)*10+6)*10+7)*10+8)*10+9 = 123456789.

Tests recursive sift_up + sift_down, in-place array swap,
parent/lchild/rchild index arithmetic, combined push/pop session
with refs.

152 baseline programs total.
2026-05-10 06:43:46 +00:00
19d0ef0f38 ocaml: phase 5.1 rolling_hash.ml baseline (Rabin-Karp, 6 "abc" matches)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Polynomial rolling hash mod 1000003 with base 257:
  - precompute base^(m-1)
  - slide window updating hash in O(1) per step
  - verify hash match with O(m) memcmp to skip false positives

  rolling_match "abcabcabcabcabcabc" "abc" = 6

Six non-overlapping copies of "abc" at positions 0,3,6,9,12,15.

Tests `for _ = 0 to m - 2 do … done` unused loop variable
(uses underscore wildcard pattern), Char.code arithmetic, mod
arithmetic with intermediate negative subtractions, complex nested
if/begin branching with inner break-via-flag.

151 baseline programs total.
2026-05-10 06:34:13 +00:00
1dd350d592 ocaml: phase 5.1 huffman.ml baseline (Huffman tree WPL = 224)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Classic CLRS Huffman code example. ADT:

  type tree = Leaf of int * char | Node of int * tree * tree

Build by repeatedly merging two lightest trees (sorted-list pq):

  let rec build_tree lst = match lst with
    | [t] -> t
    | a :: b :: rest ->
      let merged = Node (weight a + weight b, a, b) in
      build_tree (insert merged rest)

  weighted path length (= total Huffman bits):
    leaves {(5,a) (9,b) (12,c) (13,d) (16,e) (45,f)} -> 224

Tests sum-typed ADT with mixed arities, `function` keyword
pattern matching, recursive sorted insert, depth-counting recursion.

150 baseline programs total.
2026-05-10 06:21:06 +00:00
4fdf6980da ocaml: parser accepts if/match/let/fun as rhs of <- and :=
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Previously `a.(i) <- if c then x else y` failed with
"unexpected token keyword if" because parse-binop-rhs called
parse-prefix for the rhs, which doesn't accept if/match/let/fun.

Real OCaml allows full expressions on the rhs of <-/:=. Fix:
special-case prec-1 ops in parse-binop-rhs to call parse-expr-no-seq
instead of parse-prefix. The recursive parse-binop-rhs with
min-prec restored after picks up any further chained <- (since both
ops are right-associative with no higher-prec binops above them).

Manacher baseline updated to use bare `if` on rhs of <-,
removing the parens workaround from iter 235. 607/607 regressions
remain clean.
2026-05-10 06:11:57 +00:00
cccef832d9 ocaml: phase 5.1 manacher.ml baseline (longest palindrome "babadaba" = 7)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Manacher's algorithm: insert # separators (length 2n+1) to unify
odd/even cases, then maintain palindrome radii p[] alongside a
running (center, right) pair to skip work via mirror reflection.
Linear time.

  manacher "babadaba" = 7   (* witness: "abadaba", positions 1..7 *)

Note: requires parenthesizing the if-expression on the rhs of <-:

  p.(i) <- (if pm < v then pm else v)

Real OCaml parses bare `if` at <-rhs since the rhs is at expr
level; our parser places <-rhs at binop level which doesn't include
`if` / `match` / `let`. Workaround until we relax the binop
RHS grammar.

149 baseline programs total.
2026-05-10 05:58:05 +00:00
526ffbb5f0 ocaml: phase 5.1 floyd_warshall.ml baseline (4-node APSP, dist(0,3)=9)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 53s
Floyd-Warshall all-pairs shortest path with triple-nested for-loop:

  for k = 0 to n - 1 do
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
        if d.(i).(k) + d.(k).(j) < d.(i).(j) then
          d.(i).(j) <- d.(i).(k) + d.(k).(j)
      done
    done
  done

Graph (4 nodes, directed):
  0->1 weight 5, 0->3 weight 10, 1->2 weight 3, 2->3 weight 1

Direct edge 0->3 = 10, but path 0->1->2->3 = 5+3+1 = 9.

Tests 2D array via Array.init with closure, nested .(i).(j) read
+ write, triple-nested for, in-place mutation under aliasing.

148 baseline programs total.
2026-05-10 05:41:02 +00:00
99f321f532 ocaml: phase 5.1 mst_kruskal.ml baseline (5-node MST weight 11)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
Kruskal's minimum spanning tree using path-compressing union-find:

  edges (w, u, v):
    (1, 0, 1) (2, 1, 2) (3, 0, 3) (4, 2, 3) (5, 3, 4) (6, 0, 4)

After sorting by weight and greedily unioning:
  pick (1,0,1) -> components: {0,1} {2} {3} {4}
  pick (2,1,2) -> {0,1,2} {3} {4}
  pick (3,0,3) -> {0,1,2,3} {4}
  skip (4,2,3) -- already connected
  pick (5,3,4) -> {0,1,2,3,4}
  skip (6,0,4) -- already connected

  MST weight = 1 + 2 + 3 + 5 = 11

Tests List.sort with 3-tuple destructuring lambda, compare on int,
Array.init with closure, in-place array mutation in find, boolean
union returning true iff merge happened.

147 baseline programs total.
2026-05-10 05:21:14 +00:00