Skip to content

Instantly share code, notes, and snippets.

@freddiefujiwara
Created January 20, 2012 00:01
Show Gist options
  • Select an option

  • Save freddiefujiwara/1643861 to your computer and use it in GitHub Desktop.

Select an option

Save freddiefujiwara/1643861 to your computer and use it in GitHub Desktop.
knapsack problem
var items = [{w:2,v:3},{w:1,v:2},{w:3,v:4},{w:2,v:2}];
var results = [],values =[];
var MAX_W=5;
for(var start = 0; start < items.length ; start ++){
var current_w =0, current_v = 0;
var item_numbers = [];
for(var i = start ; i < items.length; i++){
if(MAX_W >= (current_w+items[i].w)){
item_numbers.push(i);
current_v += items[i].v;
current_w += items[i].w;
results.push({w:current_w,v:current_v,item_numbers:item_numbers.slice(0)});
values.push(current_v);
}
}
}
console.log(Math.max.apply(null,values));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment