If I have an array of numbers and a list of sums that total the array elements, what's the most effective approach (or at least a not a brute force hack) for determining which of the elements are included in the sum?
A simplified example might look like:
array = [6, 5, 7, 8, 6, 12, 16] sums = [14, 24, 22]
and I would want to know:
14 includes 8, 6
24 includes 5, 7, 12
22 includes 6, 16
function matchElements(arr, sums) {
var testArr;
function getSumHash() {
var hash = {},
i;
for (i = 0; i < sums.length; i++) {
hash[sums[i]] = [];
}
return hash;
}
sums = getSumHash();
// I don't have a good sense of where to start on what goes here...
return sumHash;
}
var totals = matchElements([6, 5, 7, 8, 6, 12, 16], [14,24,22]),
total;
for (total in totals) {
console.log(total + "includes", totals[total])
}
I do know that there will always be at least one correct answer and it only matters to me that the numbers check out, I do not need to pair the index where there are duplicates, only the value as it relates to the total. Is there an established function for resolving this kind of problem?
This is only a javascript question because that's the language I'm writing the solution in, this is more of a general mathematics related question as filtered through Javascript. If this is not the appropriate forum, I welcome redirection to the appropriate stack exchange site.