Last active
January 13, 2016 14:11
-
-
Save ayoola-solomon/647338790a3dd0876971 to your computer and use it in GitHub Desktop.
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
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