Skip to content

Instantly share code, notes, and snippets.

@iJustErikk
Last active December 11, 2020 01:18
Show Gist options
  • Save iJustErikk/090b52799c704de05cc9543c900c09e6 to your computer and use it in GitHub Desktop.
Save iJustErikk/090b52799c704de05cc9543c900c09e6 to your computer and use it in GitHub Desktop.
fixed bug
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