I am having a hard time reasoning around this problem. Given a set of numbers ([1, 2, 3, 4, 5, 6, 7,8, 9, 10, 11, 12]
) I want to find every possible combination that adds up to be 12.
So, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
is equal as is [1, 2, 9]
as is [12]
.
Ideally the return value is something along the lines of...
[
[1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,2],
…
]
I don't necessarily need the programing solved, just the algo or direction in the algo.
This is what I have so far:
var subsets = function (arr, total, answers, itteration) {
var answers = answers || [[0]],
itteration = itteration || 0,
thisTest = answers[itteration],
testTotal = sum(thisTest, total);
if (testTotal === total) {
if (arr.length === itteration) {
return answers;
}
return subsets(arr, total, answers, itteration++);
}
for (var i=0, i<arr.length; i++) {
thisTest.push(arr[i]);
if (sum(thisTest, total) === total) {
}
}
}
var sum = (array, total) {
var tempTotal = 0;
return array.forEach(function (el) {
return tempTotal += el;
});
}
console.log(subsets([1,2,3,4,5,6,7,8,9,10,11,12], 12));