Created
May 25, 2012 09:43
-
-
Save rd13/2786999 to your computer and use it in GitHub Desktop.
Find the best sum of numbers in an array for a given value.
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
//jsFiddle: http://jsfiddle.net/CuDzh/3/ | |
$(function() { | |
function bestSum(numbers, sum) { | |
l = function(index, total, solution) { | |
index = index ? index : 0; | |
total = total ? total : 0; | |
solution = solution ? solution : ''; | |
if (total == sum) { | |
return solution.substring(1).split(' '); | |
} else if (index < numbers.length) { | |
return l(index + 1, total, solution) || l(index + 1, (total + numbers[index]), solution + ' ' + numbers[index]); | |
} | |
return false; | |
} | |
return l(); | |
} | |
//e.g. To find the best combination of numbers that equal 6 from the 'numbers' array. | |
var numbers = [2, 2, 1, 1, 1, 3]; | |
var sum = 6; | |
console.log(bestSum(numbers, sum)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment