Last active
January 16, 2018 14:37
-
-
Save hahmed/24b6e1ee4f1c87c0d6f16c26ef6ae6fb to your computer and use it in GitHub Desktop.
Finding unique pairs in array
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
# Write a function which, given an array of integers of value greater or equal to 0, returns all unique pairs which sum to 100. | |
# | |
# Example data: | |
# | |
# input = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51] | |
# output = [[1,99], [0,100], [10,90], [51,49], [50,50]] | |
class Test | |
def remove_used(match, array) | |
array.delete_at array.index match[0] | |
array.delete_at array.index match[1] | |
array | |
end | |
def find_matching_from_array_for_val(val, array) | |
array.each_with_index do |compare, index| | |
return [val,compare] if equal_100?(val, compare) | |
end | |
nil | |
end | |
def equal_100?(val1, val2) | |
val1 + val2 == 100 | |
end | |
def perform(array) | |
# p array | |
output = Array.new | |
copy = array | |
array.each_with_index do |val, index| | |
break if (index + 1 >= array.size) | |
match = find_matching_from_array_for_val(val, copy) | |
if match | |
output << match | |
copy = remove_used(match, copy) | |
end | |
end | |
output.uniq | |
end | |
end | |
input = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51] | |
t = Test.new | |
result = t.perform(input) | |
p result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment