ocaml: phase 5.1 knapsack.ml baseline (0/1 knapsack, cap=8 -> 36)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 15s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 15s
Standard 1D 0/1 knapsack DP with reverse inner loop:
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)
values: [|6; 10; 12; 15; 20|]
weights: [|1; 2; 3; 4; 5|]
knapsack v w 8 = 36 (* take items with weights 1, 2, 5 *)
Tests for-downto + array literal access in the same hot loop.
143 baseline programs total.
This commit is contained in:
@@ -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,
|
||||
|
||||
17
lib/ocaml/baseline/knapsack.ml
Normal file
17
lib/ocaml/baseline/knapsack.ml
Normal file
@@ -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
|
||||
Reference in New Issue
Block a user