Created
February 21, 2019 19:56
-
-
Save hack3rvaillant/3e522ff2af1400b919ce000a5105fa10 to your computer and use it in GitHub Desktop.
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 find_pairs(input, sum, results = []) | |
return results.uniq if input.empty? # break condition | |
input.each_with_index do |element, i| | |
input.delete_at(i) # reduces the array size for already tried element | |
other_element = sum - element | |
index = input.index(other_element) # find other element index | |
if index.present? | |
input.delete_at(index) # reduces the array size for already tried element | |
pair = element > other_element ? [other_element, element] : [element, other_element] | |
results << pair | |
end | |
find_pairs(input, sum, results) # recursion | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment