I'm a bit late in contributing, but no one appears to have posted the obligatory JavaScript one-liner.
let input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5];
let dSum = 28;
let Result = [];
input.forEach( i=>{ input.forEach( j=>{ i+j==dSum && Result.push([i,j]); }); });
The Result
array will contain the solutions, of which there are two in this case:
[[12, 16], [16, 12]]
Generalising this to a function where values representing input
and dSum
are user-defined parameters:
pairsFromArrayWithSum = (total, Numbers)
=> Numbers.forEach(a => {
Numbers.forEach(b => {
a + b == total && Result.push([a,b]);
}); });
Then, given:
Result = [];
pairsFromArrayWithSum(50, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]);
the Result
array will contain:
[ [ 3, 47 ],
[ 7, 43 ],
[ 13, 37 ],
[ 19, 31 ],
[ 31, 19 ],
[ 37, 13 ],
[ 43, 7 ],
[ 47, 3 ] ]