This test passes validations, but how?
#Rspec
it "handles a case with an answer > 1 distance to the left" do
nearest_larger([8,2,4,3], 2).should == 0
end
#Function
def nearest_larger(arr, idx)
diff = 1
loop do
left = idx - diff
right = idx + diff
if (left >= 0) && (arr[left] > arr[idx])
return left
elsif (right < arr.length) && (arr[right] > arr[idx])
return right
elsif (left > 0) && (right >= arr.length)
return nil
end
diff += 1
end
end
I'm working through some ruby examples and I can't understand how this test passes validation. Where is 0
being returned from?
When idx
is 2 and diff
is 2 (that is, on your second loop), left
is 2 - 2 = 0
, and arr[0] == 8
, which is greater than arr[2] == 4
. The function then returns left
, which is zero.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.