Created
February 9, 2017 17:38
-
-
Save baweaver/6dc31d013c2d4eda87eb2e52a6979514 to your computer and use it in GitHub Desktop.
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
def has_pair_with_sum_brute_force(input, sum) | |
# Boolean coercion. Just returning an int (index where found) can be confusing | |
!!input.find.with_index do |value, i| | |
# All we need to do is keep the inner loop one ahead of the outer. | |
input[(i + 1)..-1].find do |sub_value| | |
value + sub_value == sum | |
end | |
end | |
end | |
def has_pair_with_sum_in_ordered_list(input, sum) | |
# We don't really care about a single item from input here, just positions | |
input.each_with_object([0, -1]) do |_, position| | |
item_sum = input[position[0]] + input[position[1]] | |
# We found a match | |
return true if item_sum == sum | |
# The pointers collided | |
return false if position[0] == input.size + position[1] | |
position[0] += 1 if item_sum < sum | |
position[1] -= 1 if item_sum > sum | |
end | |
false | |
end | |
def has_pair_with_sum_in_unordered_list(input, sum) | |
input.each_with_object(Set.new) do |value, complements| | |
return true if complements.include?(value) | |
complements.add(sum - value) | |
end | |
false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment