Skip to content

Instantly share code, notes, and snippets.

Created August 30, 2016 15:46
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 anonymous/909ee157ff66038f4e566b85d5c88c66 to your computer and use it in GitHub Desktop.
Save anonymous/909ee157ff66038f4e566b85d5c88c66 to your computer and use it in GitHub Desktop.
Knapsack Problem?
var items = [{i: 'map', w: 9, v: 150},
{i: 'compass', w: 13, v: 35},
{i: 'water', w: 153, v: 200},
{i: 'sandwich', w: 50, v: 160},
{i: 'glucose', w: 15, v: 60},
{i: 'tin', w: 68, v: 45},
{i: 'banana', w: 27, v: 60},
{i: 'apple', w: 39, v: 40},
{i: 'cheese', w: 23, v: 30},
{i: 'beer', w: 52, v: 10},
{i: 'suntan cream', w: 11, v: 70},
{i: 'camera', w: 32, v: 30},
{i: 'T-shirt', w: 24, v: 15},
{i: 'trousers', w: 48, v: 10},
{i: 'umbrella', w: 73, v: 40},
{i: 'waterproof trouser', w: 42, v: 70},
{i: 'waterproof clothes', w: 43, v: 75},
{i: 'note-case', w: 22, v: 80},
{i: 'sunglasses', w: 7, v: 20},
{i: 'towel', w: 18, v: 12},
{i: 'socks', w: 4, v: 50},
{i: 'book', w: 30, v: 10}
];
var max = 400;
items.forEach(function(e){e.r = e.v / e.w;});
items.sort(function(a,b){return b.r - a.r;});
var available = max;
var sack = [];
items.some(function(e){
if(e.w > available){
return;
}
available -= e.w;
sack.push(e);
if(!available){
return true;
}
});
sack.forEach(function(e){console.log(e.i);});
console.log('Total weight: ', max - available);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment