-
-
Save bogdanRada/7fa086dcf02924b19f22904fd1e552a2 to your computer and use it in GitHub Desktop.
Find all number pairs in a Ruby array that add up to a given number
This file contains hidden or 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
#!/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