Skip to content

Instantly share code, notes, and snippets.

@moog16
Created September 9, 2017 19:42
Show Gist options
  • Select an option

  • Save moog16/601a9a0ea50afaaa48da9fc49f8a4c83 to your computer and use it in GitHub Desktop.

Select an option

Save moog16/601a9a0ea50afaaa48da9fc49f8a4c83 to your computer and use it in GitHub Desktop.
function knapsack(vals, wts, maxWeight) {
var maxValFound = 0;
function maxVal(vals, wts, currentVal, currentWeight) {
for(var i=0; i<vals.length; i++) {
var addVal = vals[i];
var addWeight = wts[i];
if(currentWeight + addWeight > maxWeight) {
continue;
}
if(currentVal + addVal > maxValFound) {
maxValFound = currentVal + addVal;
}
var newVals = vals.slice();
newVals.splice(i, 1);
var newWeights = wts.slice();
newWeights.splice(i, 1);
maxVal(newVals, newWeights, currentVal + addVal, currentWeight + addWeight);
}
}
maxVal(vals, wts, 0, 0);
return maxValFound;
}
maxVal = 1;
vals = [1, 1, 4, 4, 5]
wts = [5, 4, 8, 9, 3]
var x = knapsack(vals, wts, 10);
console.log(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment