通常堆栈溢出是为有形问题保留的,但我正忙着解决一个难题,想知道是否有人可以解释它。我正在遍历递归并遇到了 Dave Thomas 的 Code Kata(非常酷)。我很高兴自己做出答案,然后试图减少它们,但有一个我无法弄清楚的回应:
问题:代码 Kata #2 http://codekata.pragprog.com/2007/01/kata_two_karate.html
一个有效的答案,但我不明白为什么在这里:
def chop(target, values)
# Special handling for zero and single element arrays
return -1 if values.empty?
return ((target == values[0]) ? 0 : -1) if values.length == 1
# Try the bottom half first
pos = chop(target, values[0, values.length/2])
return pos if pos != -1
# Then the upper half ... remember that the returned
# position is relative to the middle of the array.
pos = chop(target, values[values.length/2, values.length-1])
return pos + (values.length/2) if pos != -1
# Didn't find what we were looking for
return -1
end
谁能向我解释一下索引是如何支持这种递归模式的?
当我阅读它时,它会递归,直到它达到它的数字并返回 0。我一生都无法弄清楚这个东西为什么/如何吐出索引。