ocaml: phase 5.1 triangle.ml baseline (Pascal-shape min path sum, 2+3+5+1 = 11)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
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.
This commit is contained in:
@@ -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,
|
||||
|
||||
17
lib/ocaml/baseline/triangle.ml
Normal file
17
lib/ocaml/baseline/triangle.ml
Normal file
@@ -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]]
|
||||
Reference in New Issue
Block a user