Created
January 13, 2017 11:08
-
-
Save eswak/35de8a1f30d66fb73c09311851021ca9 to your computer and use it in GitHub Desktop.
JavaScript Knapsack problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://rosettacode.org/wiki/Knapsack_problem/0-1 | |
// list all available items | |
var items = [ | |
{name:"map", weight:9, value: 150}, | |
{name:"compass", weight:13, value: 35}, | |
{name:"water", weight:153, value: 200}, | |
{name:"sandwich", weight: 50, value: 160}, | |
{name:"glucose", weight:15, value: 60}, | |
{name:"tin", weight:68, value: 45}, | |
{name:"banana", weight:27, value: 60}, | |
{name:"apple", weight:39, value: 40}, | |
{name:"cheese", weight:23, value: 30}, | |
{name:"beer", weight:52, value: 10}, | |
{name:"suntan cream", weight:11, value: 70}, | |
{name:"camera", weight:32, value: 30}, | |
{name:"T-shirt", weight:24, value: 15}, | |
{name:"trousers", weight:48, value: 10}, | |
{name:"umbrella", weight:73, value: 40}, | |
{name:"waterproof trousers", weight:42, value: 70}, | |
{name:"waterproof overclothes", weight:43, value: 75}, | |
{name:"note-case", weight:22, value: 80}, | |
{name:"sunglasses", weight:7, value: 20}, | |
{name:"towel", weight:18, value: 12}, | |
{name:"socks", weight:4, value: 50}, | |
{name:"book", weight:30, value: 10} | |
]; | |
var bag = items | |
// sort items by most value per decagram first | |
.sort(function (item1, item2) { | |
var item1ValuePerWeight = item1.value / item1.weight; | |
var item2ValuePerWeight = item2.value / item2.weight; | |
return item1ValuePerWeight < item2ValuePerWeight ? 1 : -1; | |
}) | |
// push items in the bag as long as the weight doesn't exceed 400 decagrams | |
.reduce(function (bag, item) { | |
var currentBagWeight = bag.reduce(function (weight, item) { | |
weight += item.weight; | |
return weight; | |
}, 0); | |
if (currentBagWeight + item.weight < 400) { | |
bag.push(item); | |
} | |
return bag; | |
}, []); | |
// result : compute bag weight (396) | |
var bagWeight = bag.reduce(function (weight, item) { | |
weight += item.weight; | |
return weight; | |
}, 0); | |
// result : compute bag value (1030) | |
var bagValue = bag.reduce(function (value, item) { | |
value += item.value; | |
return value; | |
}, 0); | |
// print resoult | |
console.log('weight: ' + bagWeight + '\nvalue: ' + bagValue + '\nitems: ' + bag.map(function (item) { return item.name; }).join(', ')); | |
// output: | |
// weight: 396 | |
// value: 1030 | |
// items: map, socks, suntan cream, glucose, note-case, sandwich, sunglasses, compass, banana, waterproof overclothes, waterproof trousers, water | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment