Skip to content

Instantly share code, notes, and snippets.

@alexislagante
Created November 8, 2015 09:34
Show Gist options
  • Save alexislagante/3e1ff61fe9936bbc65a8 to your computer and use it in GitHub Desktop.
Save alexislagante/3e1ff61fe9936bbc65a8 to your computer and use it in GitHub Desktop.
Unbounded Knapsack
function unboundedKnapsack(tuples, capacity) {
var result = [0];
for (var i=1; i<=capacity; i++) {
var maxValue = tuples.reduce(function(max, curr) {
var val = 0;
var weight = curr[0];
var cost = curr[1];
if (cost>0 && weight<=i) {
if (weight==0) {
val = Number.POSITIVE_INFINITY;
} else {
val = cost + result[i-weight];
}
}
max = Math.max(max, val);
return max;
}, 0);
result.push(maxValue);
}
return result[capacity];
}
unboundedKnapsack([[7,160],[3,90],[2,15]], 20);
unboundedKnapsack([[0,160],[3,90],[2,15]], 20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment