From 5b38f4d4998bd7d0d2730278cfc21eaefd221856 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 15:32:11 +0000 Subject: [PATCH] ocaml: phase 5.1 triangle.ml baseline (Pascal-shape min path sum, 2+3+5+1 = 11) Bottom-up DP minimum-path through a triangle: 2 3 4 6 5 7 4 1 8 3 let min_path_triangle rows = initialise dp from last row; for r = n - 2 downto 0 do for c = 0 to row_len - 1 do dp.(c) <- row.(c) + min(dp.(c), dp.(c+1)) done done; dp.(0) The optimal path 2 -> 3 -> 5 -> 1 sums to 11. Tests downto loop, Array.of_list inside loop body, nested arr.(i) reads + writes, and inline if-then-else for min. 74 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/triangle.ml | 17 +++++++++++++++++ plans/ocaml-on-sx.md | 11 +++++++++++ 3 files changed, 29 insertions(+) create mode 100644 lib/ocaml/baseline/triangle.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 818e582e..953cb99a 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -70,6 +70,7 @@ "zip_unzip.ml": 1000, "sieve.ml": 15, "sum_squares.ml": 385, + "triangle.ml": 11, "twosum.ml": 5, "unique_set.ml": 9, "validate.ml": 417, diff --git a/lib/ocaml/baseline/triangle.ml b/lib/ocaml/baseline/triangle.ml new file mode 100644 index 00000000..bac3483e --- /dev/null +++ b/lib/ocaml/baseline/triangle.ml @@ -0,0 +1,17 @@ +let min_path_triangle rows = + let n = List.length rows in + let dp = Array.make n 0 in + let last = List.nth rows (n - 1) in + let i = ref 0 in + List.iter (fun x -> dp.(!i) <- x; i := !i + 1) last; + for r = n - 2 downto 0 do + let row = Array.of_list (List.nth rows r) in + for c = 0 to Array.length row - 1 do + dp.(c) <- row.(c) + (if dp.(c) < dp.(c + 1) then dp.(c) else dp.(c + 1)) + done + done; + dp.(0) + +;; + +min_path_triangle [[2]; [3; 4]; [6; 5; 7]; [4; 1; 8; 3]] diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 9fee206a..0e36da8e 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,17 @@ _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 — triangle.ml baseline (Pascal-shape min path + sum, 2+3+5+1 = 11). Bottom-up DP over the triangle: + 2 + 3 4 + 6 5 7 + 4 1 8 3 + Initialise dp from last row, then for each row above, replace + dp.(c) with row.(c) + min(dp.(c), dp.(c+1)). Final answer in + dp.(0). Tests downto loop, Array.of_list inside loop, nested + arr.(i) reads + writes, and List.nth iteration. 74 baseline + programs total. - 2026-05-09 Phase 5.1 — max_path_tree.ml baseline (max root-to-leaf sum in a binary tree, 1+3+7 = 11). Recursive ADT `tree = Leaf | Node of int * tree * tree`. max_path returns 0 at Leaf, else