Created
September 26, 2017 18:47
-
-
Save batogov/c00925ed697f6179a4a54e99e9c11b68 to your computer and use it in GitHub Desktop.
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
function comp(firstItem, secondItem) { | |
const firstCoeff = firstItem['value'] / firstItem['weight']; | |
const secondCoeff = secondItem['value'] / secondItem['weight']; | |
return secondCoeff - firstCoeff; | |
} | |
function knapsack(w, items) { | |
let result = []; | |
items = items.sort(comp); | |
for (let i = 0, length = items.length; i < length; i++) { | |
if (w >= items[i]['weight']) { | |
result.push(items[i]); | |
w -= items[i]['weight']; | |
} else { | |
break; | |
} | |
} | |
return result; | |
} | |
const w = 80; | |
const items = [ | |
{'weight': 15, 'value': 60}, | |
{'weight': 50, 'value': 100}, | |
{'weight': 30, 'value': 90} | |
]; | |
const result = knapsack(w, items); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment