Skip to content

Instantly share code, notes, and snippets.

@mrandrewmills
Last active August 9, 2021 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrandrewmills/39b445187e98c6591258b8282c680840 to your computer and use it in GitHub Desktop.
Save mrandrewmills/39b445187e98c6591258b8282c680840 to your computer and use it in GitHub Desktop.
Solving The Knapsack Problem
// inspired by Academind's "JavaScript Algorithms Crash Course"
// see https://www.youtube.com/watch?v=JgWm6sQwS_I for more like this
// Imagine you have a list of items, and each item has a value and a weight associated with it.
items = [
{ id: "b", val: 6, w: 8 },
{ id: "a", val: 10, w: 3 },
{ id: "c", val: 3, w: 3 },
];
// Original example was pre-sorted by value decreasing, but I mixed up the order above to make it more realistic.
items.sort( function(b,a){
if (a.val > b.val) return 1;
if (a.val < b.val) return -1;
// if two items have same value, we can rank by weight (lightest item first)!
if (a.val == b.val) {
if (a.w > b.w) return 1;
if (a.w < b.w) return -1;
}
return 0; // if equal in value and wt, leave them be
});
// How can we get the highest total value of items in the bag, without exceeding its weight capacity?
// first, we need a bag
function Bag(wl){
let obj = {};
obj.wtLimit = wl;
obj.contents = [];
// then we figure out how to stuff bag without exceeding its limit
obj.stuffBag = function(items){
items.forEach( function(item){
if (item.w <= obj.wtLimit) {
obj.contents.push(item);
obj.wtLimit -= item.w;
}
});
};
return obj;
}
// nothing to it, but to do it.
let myBag = new Bag(8);
myBag.stuffBag(items);
console.log( myBag.contents );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment