Hello forum,
I am currently investigating a particular problem in the Rosetta Code section, Knapsack Problem/Unbounded, and the particular solution provided to the Hint section in the worst-case scenario.
Below is the solution provided…
function knapsackUnbounded(items, maxweight, maxvolume) {
var n = items.length;
var best_value = 0;
var count = new Array(n)
var best = new Array(n)
function recurseKnapsack(i, value, weight, volume) {
var j, m1, m2, m;
if (i == n) {
if (value > best_value) {
best_value = value;
for (j = 0; j < n; j++) {
best[j] = count[j];
}
}
return;
}
m1 = Math.floor(weight / items[i].weight);
m2 = Math.floor(volume / items[i].volume);
m = m1 < m2 ? m1 : m2;
for (count[i] = m; count[i] >= 0; count[i]--) {
recurseKnapsack(
i + 1,
value + count[i] * items[i].value,
weight - count[i] * items[i].weight,
volume - count[i] * items[i].volume
);
}
}
recurseKnapsack(0, 0, maxweight, maxvolume);
return best_value;
}
console.log(`Case 4 best_val: ${knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35)}\n`);
This is the supposed issue with the solution: a discrepancy between the solution and the presented value, of 600 (best_value_solution = 75300, best_value_presentedValue = 75900)…
Is there another way to resolve this discrepancy given the parameters (in JSON/ dictionary), and/or improve the proposed solution?
Thank you for your input