Skip to content

Instantly share code, notes, and snippets.

@hack3rvaillant
Created February 21, 2019 19:56
Show Gist options
  • Save hack3rvaillant/3e522ff2af1400b919ce000a5105fa10 to your computer and use it in GitHub Desktop.
Save hack3rvaillant/3e522ff2af1400b919ce000a5105fa10 to your computer and use it in GitHub Desktop.
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