Skip to content

Instantly share code, notes, and snippets.

@vitalii-komenda
Created June 8, 2021 10:47
Show Gist options
  • Save vitalii-komenda/fdebce3e4a9e4b4383d698a04da3fef5 to your computer and use it in GitHub Desktop.
Save vitalii-komenda/fdebce3e4a9e4b4383d698a04da3fef5 to your computer and use it in GitHub Desktop.
items=[{v: 5, w: 10}, {v: 1, w: 1}, {v: 3, w: 4}]
knp = (items, selected, maxWeight, val)=>{
if (maxWeight === 0) return [val, selected];
if (maxWeight < 0) return [0, selected];
if (!items.length) return [val, selected];
let last = items[items.length-1];
let including = knp(items.slice(0, -1), selected.concat(last), maxWeight - last.w, val+last.v);
let notIncluding = knp(items.slice(0, -1), selected, maxWeight, val);
return including[0] > notIncluding[0] ? including : notIncluding;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment