Skip to content

Instantly share code, notes, and snippets.

@kfox
Created March 5, 2014 04:07
Show Gist options
  • Save kfox/9360968 to your computer and use it in GitHub Desktop.
Save kfox/9360968 to your computer and use it in GitHub Desktop.
Find all number pairs in a Ruby array that add up to a given number
#!/usr/bin/env ruby
numbers = [2, 6, 4, 8, 8, 9]
sum = ARGV.empty? ? 10 : ARGV.first.to_i
def sum_exists(numbers, sum)
Array(numbers).combination(2).find_all { |x, y| x + y == sum } || []
end
result = sum_exists(numbers, sum)
puts "given this array: #{numbers.inspect}"
puts "#{result.size} pairs add up to #{sum}: #{result.inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment