Sums of pairs
Write a function that takes a collection of numbers and a target number. Return all pairs of numbers found in the collection that sum up to the target number.
Examples
(sums-of-pairs [2 4 5 6] 8) ;=> [[2 6]]
(sums-of-pairs [3 2 0 1 1 5] 5) ;=> [[2 3] [0 5]]
(sums-of-pairs [1 3 2 3 4 5] 7) ;=> [[3 4] [3 4] [2 5]]
Notes
- There can be duplicate numbers.
- Each pair should be sorted.
Thanks to this site for the challenge idea where it is considered Expert level in JavaScript.
Please submit your solutions as comments on this gist.
@mchampine you bring up an interesting point regarding duplicates, which made me reflect on the problem statement, and what constitutes a candidate pair (a pair to be tested for adding up to the target sum)
.
"Return all pairs found in the collection that sum up to the target number" : I wondered initially if an object can be paired with itself, but the first example shows otherwise as (4,4) is not part of the result but adds up to 8. So once an object is picked, pair it with all others but not itself.
However, input lists can have duplicates, and therefore a number could be paired with itself in some cases, e.g. if the first example had a duplicate 4, (4,4) would indeed be in the result.
Therefore when building the candidate pairs list from an input list that may have duplicates, the position in the list is the best (only?) way to differentiate two objects, not their value. For me,
map-indexed
came to the rescue to build the pairs: all objects having a different index are paired (once only, by constraining indexes in e.g. ascending order in a looping construct).