Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active December 18, 2015 21:19
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 jremmen/5846579 to your computer and use it in GitHub Desktop.
Save jremmen/5846579 to your computer and use it in GitHub Desktop.
js: optimistic value using linear relaxtion
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