-
-
Save seanhandley/a47a0cb33c9ee6c142e2aaebb2702ffd to your computer and use it in GitHub Desktop.
Write a function that takes an array of integers and a target sum, and returns all unique quadruplets [a, b, c, d] in the array such that a + b + c + d = target. If it's impossible, return an empty array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def four_sum(collection, target) | |
collection.combination(4). | |
uniq. | |
select { |combination| combination.sum == target }. | |
map(&:sort). | |
sort | |
end | |
four_sum([1, 0, -1, 0, -2, 2], 0) | |
# => [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] | |
four_sum([], 0) | |
# => [] | |
four_sum([1, -2, -5, -4, -3, 3, 3, 5], -11) | |
# => [[-5, -4, -3, 1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment