Skip to content

Instantly share code, notes, and snippets.

@ayoola-solomon
Last active January 13, 2016 14:11
Show Gist options
  • Save ayoola-solomon/647338790a3dd0876971 to your computer and use it in GitHub Desktop.
Save ayoola-solomon/647338790a3dd0876971 to your computer and use it in GitHub Desktop.
var input = [4, 900, 500, 498, 4];
function walrusWeight(input) {
var target = 1000;
var optimum = 0;
var sums = [];
sums.push(optimum);
for(var i=0; i < input.length; i++) {
var newSums = [];
for(var j=0; j < sums.length; j++) {
var newSum = sums[j] + input[i];
if (newSum <= target) {
newSums.push(newSum);
if (newSum > optimum) {
optimum = newSum;
}
} else if ((Math.abs(target-newSum) < Math.abs(target-optimum)) || (Math.abs(target-newSum) == Math.abs(target-optimum) && newSum > optimum)) {
optimum = newSum;
}
}
sums = sums.concat(newSums);
}
return optimum;
}
walrusWeight(input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment