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.
Thanks @KingCode, but it wasn't an original idea, I must have seen that somewhere.
I do like your rewrite! 👍
It was dissoc'ing because it wasn't exactly clear to me what should happen when you have duplicates.
Example 3 makes it clear for the case when one number (3) in the pairs is duplicated, but what should happen if the other number (4) was duplicated too?
Duplicates weren't allowed in the original problem statement, so had no further examples to check.
Without duplicates all solutions are simpler, in the O(n) solution
matches
could be a set instead of map.Also to note is that the original problem statement had an extra spin: they wanted the pairs in the order of "completes the cycle first" as they call it. ie. in example 3 they want:
[[3 4] [3 4] [2 5]]
not[[3 4] [2 5] [3 4]]
because although
2
comes before the second3
, the pair of3
,4
comes before the pair of2
,5
, so the second[3 4]
"completes" before[2 5]
.That would make the "normal" 2 nested loops solutions incorrect, so you would have to do some extra work to take care of that.