Reputation: 459
The error is on line 12 and I'm not sure why I can't add the numbers. Any help is much appreciated.
Instructions: 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
.
def two_sum(nums)
idx1 = 0
idx2 = 1
while idx1 < nums.length
if nums[idx1] + nums[idx2] == 0
return [idx1, idx2]
end
idx2 += 1
if idx2 == nums.length
idx1 += 1
idx2 = idx1 + 1
end
end
return nil
end
puts("two_sum([1, 3, 5, -3]) == [1, 3]: #{two_sum([1, 3, 5, -3]) == [1, 3]}")
puts("two_sum([1, 3, 5]) == nil: #{two_sum([1, 3, 5]) == nil}")
Upvotes: 1
Views: 6042
Reputation: 83680
idx2
could overflow capacity of your array:
Imagine. nums = [1,2,3]
, so nums.length
is 3, idx1 = 1
, idx2 = 2
idx2 += 1 # ok now idx2 is 3
if idx2 == nums.length # ok true, idx2 == 3
idx1 += 1 # mmm, cool idx1 now 2
idx2 = idx1 + 1 # idx2 is 3
end
So in next iteration you will call
nums[idx2]
# same as
nums[3]
# ERROR! there is only 3 numbers in nums
And try to understand this code
def two_sums(nums)
nums[0..-2].each.with_index do |n,i|
nums[i+1..-1].each.with_index do |m,j|
return [i, i+j+1] if m + n == 0
end
end
nil
end
Upvotes: 2