Last active
August 23, 2018 00:52
-
-
Save CodePint/fdd8c5d340b1087dfed094065fccd284 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 sum_pairs(numbers, sum) | |
seen = Array.new | |
numbers.each do |n| | |
if seen.include?(sum - n) | |
return [sum - n, n] | |
end | |
seen << n | |
end | |
nil | |
end |
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
require 'pry' | |
=begin | |
Sum of Pairs | |
Given a list of integers and a single sum value, return the first two values | |
(parse from the left please) in order of appearance that add up to form the sum. | |
sum_pairs([11, 3, 7, 5], 10) | |
# ^--^ 3 + 7 = 10 | |
== [3, 7] | |
sum_pairs([4, 3, 2, 3, 4], 6) | |
# ^-----^ 4 + 2 = 6, indices: 0, 2 * | |
# ^-----^ 3 + 3 = 6, indices: 1, 3 | |
# ^-----^ 2 + 4 = 6, indices: 2, 4 | |
# * entire pair is earlier, and therefore is the correct answer | |
== [4, 2] | |
sum_pairs([0, 0, -2, 3], 2) | |
# there are no pairs of values that can be added to produce 2. | |
== None/nil/undefined (Based on the language) | |
sum_pairs([10, 5, 2, 3, 7, 5], 10) | |
# ^-----------^ 5 + 5 = 10, indices: 1, 5 | |
# ^--^ 3 + 7 = 10, indices: 3, 4 * | |
# * entire pair is earlier, and therefore is the correct answer | |
== [3, 7] | |
Negative numbers and duplicate numbers can and will appear. | |
NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out | |
=end | |
def sum_pairs(ints, s) | |
first_int_index = 0 | |
possible_pairs = [] | |
while (first_int_index != ints.length - 1) | |
first_int = ints[first_int_index] | |
ints.each_with_index do |int, index| | |
if ((first_int + int) == s) && (index > first_int_index) | |
possible_pairs << {first_int: first_int, first_int_index: first_int_index, second_int: int, second_int_index: index} | |
end | |
end | |
first_int_index += 1 | |
end | |
earliest_pair = possible_pairs.min_by {|pair| pair[:second_int_index]} | |
if possible_pairs.empty? | |
return nil | |
else | |
return [earliest_pair[:first_int], earliest_pair[:second_int]] | |
end | |
end | |
return_value = sum_pairs([10, 5, 2, 3, 7, 5], 10) | |
binding.pry | |
puts "break" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment