diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 9788d392..c6706fe0 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -60,6 +60,7 @@ "zip_unzip.ml": 1000, "sieve.ml": 15, "sum_squares.ml": 385, + "twosum.ml": 5, "unique_set.ml": 9, "validate.ml": 417, "word_count.ml": 3 diff --git a/lib/ocaml/baseline/twosum.ml b/lib/ocaml/baseline/twosum.ml new file mode 100644 index 00000000..a6011476 --- /dev/null +++ b/lib/ocaml/baseline/twosum.ml @@ -0,0 +1,17 @@ +let twosum xs target = + let h = Hashtbl.create 8 in + let result = ref (-1, -1) in + List.iteri (fun i x -> + let need = target - x in + match Hashtbl.find_opt h need with + | Some j -> result := (j, i) + | None -> Hashtbl.add h x i + ) xs; + !result + +;; + +let (i1, j1) = twosum [2;7;11;15] 9 in +let (i2, j2) = twosum [3;2;4] 6 in +let (i3, j3) = twosum [3;3] 6 in +i1 + j1 + i2 + j2 + i3 + j3 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index acf3e929..9eee200c 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 — twosum.ml baseline (LeetCode #1, hashtable + one-pass, index-sum 1+3+1 = 5). Walks list with List.iteri, + checking if `target - x` is already in the hashtable; if yes, the + earlier index plus current is the answer; otherwise record the + current pair. Three test cases: + [2;7;11;15] target 9 → (0, 1) + [3;2;4] target 6 → (1, 2) + [3;3] target 6 → (0, 1) + Sum of i+j over each pair: 1+3+1 = 5. Tests Hashtbl.find_opt / + add + List.iteri + tuple destructuring on let-binding (iter 98). + 63 baseline programs total. - 2026-05-09 Phase 5.1 — bisect.ml baseline (root-finding via bisection, sqrt(2) * 100 = 141). 50 iterations of bisection searching for x^2 - 2 = 0 in [1, 2]. Tests higher-order function