Usually stack overflow is reserved for tangible problems, but I am having wrapping my head around a puzzle and was wondering if anyone could explain it. I am going over recursion and came across Dave Thomas’s Code Kata (very cool). I am having fun making my own answers, then trying to whittle them down, but there is one response that I can’t figure out:
Problem: Code Kata #2 http://codekata.pragprog.com/2007/01/kata_two_karate.html
An answer that works, but I can’t understand why is here:
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
Can anyone please explain to me how the index makes it way back up this recursion pattern?
As I read it, it recurses until it hits its number and returns 0. I can’t figure out for the life of me why/how this thing spits back out the index.
I find that the best way to work through recursive code like this is to start with the return statements. The “
return pos + (values.length/2) if pos != -1” line is where the magic happens.Restating the code in English: “Add the position of the found element (0 or a positive number) to the offset of the given array within the original array”.
Basically, it is called several times on the way back up the call chain, acting as an accumulator for the final answer. To see this in action, try this: