Last active
December 18, 2015 21:19
-
-
Save jremmen/5846579 to your computer and use it in GitHub Desktop.
js: optimistic value using linear relaxtion
This file contains hidden or 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 generateSortedWorth() { | |
return options.values.map(function(x, i) { | |
return { | |
index: i, | |
worth: x / options.weights[i], | |
}; | |
}).sort(function(a, b) { | |
return a.worth > b.worth ? -1 : 1; | |
}); | |
} | |
function sortByWorth(list) { | |
return options.worth.map(function(w) { | |
return list[w.index]; | |
}); | |
} | |
function calculateOptimisticValue() { | |
var estimate = { | |
value: 0, | |
weight: 0 | |
}; | |
for(i = 0; i < options.values.length - 1; i++) { | |
if(estimate.weight == options.capacity) return estimate; | |
else if(options.weights[i] + estimate.weight <= options.capacity) { | |
estimate.value += options.values[i]; | |
estimate.weight += options.weights[i]; | |
} | |
else if(options.weights[i] + estimate.weight > options.capacity) { | |
estimate.value += options.values[i] / ((options.weights[i] + estimate.weight) - options.capacity); | |
estimate.weight += options.capacity % estimate.weight; | |
} else { | |
return estimate; | |
} | |
} | |
} | |
var options = { | |
values: [4, 11, 19, 4, 12, 3], | |
weights: [4, 5, 8, 3, 8, 5], | |
capacity: 19 | |
} | |
options.worth = generateSortedWorth(); | |
options.values = sortByWorth(options.values); | |
options.weights = sortByWorth(options.weights); | |
calculateOptimisticValue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment