Last active
November 19, 2017 13:25
-
-
Save dharshan/63534d51a0386ba5a7ff17f4910e7a84 to your computer and use it in GitHub Desktop.
Find any pairs of numbers in a sequence that add up to sum N (Using builtin combination method)
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
##### OUTPUT | |
1 | |
Enter comma seperated integers | |
1,2,3,4,6,7,8 | |
Enter pair sum | |
10 | |
[[2, 8], [3, 7], [4, 6]] | |
2 | |
Enter comma seperated integers | |
1,2,3,4,6,7,8 | |
Enter pair sum | |
5 | |
[[1, 4], [2, 3]] | |
3 | |
Enter comma seperated integers | |
1,2,3,4,6,7,8 | |
Enter pair sum | |
20 | |
[] | |
4 | |
Enter comma seperated integers | |
1,2,3,4,6,7,a | |
Invalid Input (Only Integers allowed) |
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
# 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) | |
# Using built-in function combination to check and compare sum pair value | |
class CheckPairs | |
# Base class to instantiate utility class | |
def find_pairs | |
nums,sum = user_input | |
num_pairs = NumPairs.new(nums, sum) | |
pairs = num_pairs.pairs | |
p 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 | |
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 pairs | |
@numbers.combination(2).select { |x, y| x + y == @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