Last active
December 11, 2020 01:18
-
-
Save iJustErikk/090b52799c704de05cc9543c900c09e6 to your computer and use it in GitHub Desktop.
fixed bug
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
const knapsack = (vals, weights, limit, memo = new Map()) => { | |
// sub problems are going to be whether we take something or | |
if (vals.length === 0) return 0; | |
if (memo.has(`${vals}${weights}`)) return memo.get(`${vals}${weights}`); | |
const currentWeight = weights[0]; | |
const currentVal = vals[0]; | |
const leftOverWeight = limit - currentWeight; | |
// if we cant take first item | |
if (leftOverWeight < 0) return knapsack(vals.slice(1), weights.slice(1), limit, memo); | |
// first call is we dont take it, second we do | |
// regardless of taking it, both arrays get sliced | |
// if we do, limit gets lowered | |
memo.set(`${vals}${weights}`, Math.max(knapsack(vals.slice(1), weights.slice(1), limit, memo), | |
currentVal + knapsack(vals.slice(1), weights.slice(1), leftOverWeight, memo))); | |
return memo.get(`${vals}${weights}`); | |
}; | |
// recursive 0/1 knapsack | |
// memoization does not help much | |
// tabulation is definitely faster | |
console.log(knapsack([1, 2, 5, 9], [1, 4, 4, 10], 9)); // 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment