Created
November 8, 2015 09:34
-
-
Save alexislagante/3e1ff61fe9936bbc65a8 to your computer and use it in GitHub Desktop.
Unbounded Knapsack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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