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.
I wanted to use the
(= target (+ a b))
relation to find the matching pairs rather than as a filter after generating the combinations.Also, I'm making the additional assumption that a number can appear more than twice and each of the resulting pairs must appear in the result.
Once I was done with this, I took a look back and realized that the problem statement can be mapped fairly cleanly to relational programming.
Note that this one ignores the
(= a b)
case. The easiest way to fix it that I can think of is to reusematched-self
from the previous snippet, but I left that out for now while I try to come up with a purecore.logic
solution.I'd appreciate any suggestions on how to do that.