Created
September 9, 2017 19:42
-
-
Save moog16/601a9a0ea50afaaa48da9fc49f8a4c83 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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