Skip to content

Instantly share code, notes, and snippets.

@OrangeCrush
Created November 30, 2018 19:00
Show Gist options
  • Save OrangeCrush/29e8ed08c4274e00538817f82628ac37 to your computer and use it in GitHub Desktop.
Save OrangeCrush/29e8ed08c4274e00538817f82628ac37 to your computer and use it in GitHub Desktop.
My Solution to the classic napsack problem
// Dollars to notebooks
var valueMap = {
5: 6,
10: 13,
1: 1
};
// How much money you are allowed
var money = 17;
// Save best values
best = 0;
list = [];
left = 0;
function canBuyAny(moneyLeft) {
return Object.keys(valueMap).filter(function(x){
return moneyLeft >= x;
}).length > 0;
}
function napsack(moneyLeft, bought){
if(canBuyAny(moneyLeft)){
Object.keys(valueMap).forEach(function(x) {
if(x <= moneyLeft) {
return napsack(moneyLeft - x, [x].concat(bought.slice()));
}
});
} else {
let sum = bought.reduce((accum, x) => +accum + valueMap[x] , 0);
if(sum > best){
list = bought;
best = sum;
left = moneyLeft;
}
return bought;
}
}
napsack(money, []);
console.log(`Money Left: ${left}; Prices paid: ${list.join(', ')}; Total Items: ${best}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment