diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index a3a88858..ebee2b32 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -81,6 +81,7 @@ "json_pretty.ml": 24, "kadane.ml": 6, "kmp.ml": 5, + "knapsack.ml": 36, "lambda_calc.ml": 7, "lcs.ml": 4, "majority_vote.ml": 4, diff --git a/lib/ocaml/baseline/knapsack.ml b/lib/ocaml/baseline/knapsack.ml new file mode 100644 index 00000000..c889825a --- /dev/null +++ b/lib/ocaml/baseline/knapsack.ml @@ -0,0 +1,17 @@ +let knapsack values weights cap = + let n = Array.length values in + let dp = Array.make (cap + 1) 0 in + for i = 0 to n - 1 do + let v = values.(i) and w = weights.(i) in + for c = cap downto w do + let take = dp.(c - w) + v in + if take > dp.(c) then dp.(c) <- take + done + done; + dp.(cap) + +;; + +let v = [|6; 10; 12; 15; 20|] in +let w = [|1; 2; 3; 4; 5|] in +knapsack v w 8 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 2463a2e2..9338f7cc 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,14 @@ _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 — knapsack.ml baseline (0/1 knapsack DP, + cap=8 with values [|6;10;12;15;20|] and weights [|1;2;3;4;5|] + → max value 36). 1D rolling DP: outer loop over items, inner + for-downto so each item used at most once. Optimal pack {1,2,5} + weighing 8 with value 36 (also matches 6+10+20). Tests + `for c = cap downto w do … done` reverse iteration plus + array literal access in the same hot loop. 143 baseline + programs total. - 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