此测试通过验证,但如何?
#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
我正在研究一些ruby示例,我无法理解此测试如何通过验证。从0
返回的位置是什么?
答案 0 :(得分:0)
当idx
为2且diff
为2时(即第二次循环播放),left
为2 - 2 = 0
,arr[0] == 8
为arr[2] == 4
大于left
。然后该函数返回{{1}},该值为零。