From fed07059a3ccbc95ee944119ce30668902ac3391 Mon Sep 17 00:00:00 2001 From: giles Date: Mon, 11 May 2026 05:44:38 +0000 Subject: [PATCH] ocaml: phase 5.1 gas_station.ml baseline (circular tour start = 3) Classic O(n) greedy gas-station algorithm: walk once, tracking total = sum of (gas[i] - cost[i]) -- if negative, no answer curr = running tank since start -- on negative, advance start past i+1 and reset if total < 0 then -1 else start For gas = [1;2;3;4;5], cost = [3;4;5;1;2], unique start = 3. Tests `total` + `curr` parallel accumulators, reset-on-failure pattern. 202 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/gas_station.ml | 21 +++++++++++++++++++++ plans/ocaml-on-sx.md | 8 ++++++++ 3 files changed, 30 insertions(+) create mode 100644 lib/ocaml/baseline/gas_station.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 255be66a..467d28c6 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -74,6 +74,7 @@ "fib_mod.ml": 391360, "fraction.ml": 7, "frequency.ml": 5, + "gas_station.ml": 3, "gcd_lcm.ml": 60, "gray_code.ml": 136, "grep_count.ml": 3, diff --git a/lib/ocaml/baseline/gas_station.ml b/lib/ocaml/baseline/gas_station.ml new file mode 100644 index 00000000..8f18870b --- /dev/null +++ b/lib/ocaml/baseline/gas_station.ml @@ -0,0 +1,21 @@ +let gas_circuit gas cost = + let n = Array.length gas in + let total = ref 0 in + let curr = ref 0 in + let start = ref 0 in + for i = 0 to n - 1 do + let diff = gas.(i) - cost.(i) in + total := !total + diff; + curr := !curr + diff; + if !curr < 0 then begin + start := i + 1; + curr := 0 + end + done; + if !total < 0 then -1 else !start + +;; + +let gas = [| 1; 2; 3; 4; 5 |] in +let cost = [| 3; 4; 5; 1; 2 |] in +gas_circuit gas cost diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 2f2ff25a..c5c26809 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-11 Phase 5.1 — gas_station.ml baseline (find unique start + station for circular gas tour, gas=[1;2;3;4;5] cost=[3;4;5;1;2] + → start at index 3). Classic O(n) greedy: walk once tracking the + total tank delta (if negative, no solution → -1) and a running + tank that resets to 0 when it goes negative, advancing start + past the failing index. From station 3: tank 3,3+5,3+5−3,… + succeeds. Tests `total` + `curr` parallel accumulators, reset- + on-failure pattern. 202 baseline programs total. - 2026-05-11 Phase 5.1 — min_jumps.ml baseline (greedy BFS-like min jumps to reach end of [2;3;1;1;2;4;2;0;1;1] = 4). At each position track the farthest reach within the current "BFS