Skip to content

Instantly share code, notes, and snippets.

@dharshan
Last active November 29, 2017 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharshan/fe49fca027f17e2507932983a5c07458 to your computer and use it in GitHub Desktop.
Save dharshan/fe49fca027f17e2507932983a5c07458 to your computer and use it in GitHub Desktop.
Find any pairs of numbers in a sequence that add up to sum N
#### OUTPUT
1
Enter comma seperated integers
1,2,3,4,6,7,8
Enter pair sum
10
((2, 8), (3, 7), (4, 6), (6, 4), (7, 3), (8, 2))
2
Enter comma seperated integers
1,2,3,4,6,7,8
Enter pair sum
5
((1, 4), (2, 3), (3, 2), (4, 1))
3
Enter comma seperated integers
1,2,3,4,6,7,8
Enter pair sum
20
(No pairs)
4
Enter comma seperated integers
1,2,3,4,6,7,p
Invalid Input (Only Integers allowed)
# Find any pairs of numbers in a sequence that add up to sum N.
# Given input 1, 8, 2, 3, 5, 7
# Expected Output (8,2), (3, 7)
# Accept numbers and store it into array
# Take one element from array and compare it to rest of the elements
# to find resulting element
class CheckPairs
# Base class to instantiate utility class
def find_pairs
nums, sum = user_input
num_pairs = NumPairs.new(nums, sum)
pairs = num_pairs.get_pairs
format_output(pairs)
end
def user_input # Takes user input and returns to calling function as arrays
p 'Enter comma seperated integers'
nums = gets.chomp
if nums.split(',').join('').scan(/\D/).empty?
p 'Enter pair sum'
sum = gets.chomp.to_i
return [nums, sum]
else
p 'Invalid Input (Only Integers allowed)'
exit
end
end
def format_output(output) # convert array to string and replace [ ] with ( )
return p '(No pairs)' if output.empty?
output = output.to_s
output = output.tr('[','(').tr(']',')')
p output
end
end
class NumPairs
# Utility class to perform required functions
def initialize(numbers, sum) # Initialize numbers and sum
@numbers = numbers.split(',').map(&:to_i).uniq
@sum = sum.to_i
end
def get_pairs
pairs_array = []
@numbers.each do |num|
temp_array = @numbers.reject { |a| a == num }
pairs_array << pairs(num,temp_array)
end
pairs_array.flatten(1).uniq
end
def pairs(num, my_array)
pairs = []
my_array.each do |a|
pairs << [num, a] if check_sum(num, a)
end
pairs
end
def check_sum(num1, num2)
return true if num1 + num2 == @sum
end
end
pairs = CheckPairs.new
pairs.find_pairs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment