Skip to content

Instantly share code, notes, and snippets.

@barbchoy
Created October 2, 2017 05:30
Show Gist options
  • Save barbchoy/92005fc33212bd02c6daeee85cfd03c2 to your computer and use it in GitHub Desktop.
Save barbchoy/92005fc33212bd02c6daeee85cfd03c2 to your computer and use it in GitHub Desktop.
two_sum created by barbchoy - https://repl.it/Br7V/3198
# Write a method that takes an array of numbers. If a pair of numbers
# in the array sums to zero, return the positions of those two numbers.
# If no pair of numbers sums to zero, return `nil`.
#
# Difficulty: medium.
def two_sum(nums)
pos=[]
i=0
while i<nums.length
j=0
sum_of_two_nums=0
while j<nums.length
sum_of_two_nums=nums[i]+nums[j]
if sum_of_two_nums==0
pos=[i,j]
return pos
end
j+=1
end
i+=1
end
return nil
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts("\nTests for #two_sum")
puts("===============================================")
puts(
'two_sum([1, 3, 5, -3]) == [1, 3]: ' + (two_sum([1, 3, 5, -3]) == [1, 3]).to_s
)
puts(
'two_sum([1, 3, 5]) == nil: ' + (two_sum([1, 3, 5]) == nil).to_s
)
puts(
'two_sum([1, 3, 5, -5]) == [2,3]: ' + (two_sum([1, 3, 5, -5]) == [2,3]).to_s
)
puts("===============================================")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment