Skip to content

Instantly share code, notes, and snippets.

@rd13
Created May 25, 2012 09:43
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 rd13/2786999 to your computer and use it in GitHub Desktop.
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.
//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