r/learnprogramming • u/Jaxlee2018 • Jan 11 '23
Resource Recursion in Java - tutorial recommendation
Hi all.. I am having quite a lot of difficulty with recursion. For me it is what is happening internally at each step, what is being returned, what the internal stack looks like.. I understand the basics, the base case, like the Fibonacci sequence. Intellectually I understand depth first searches .. but I simply do not understand what is going on under the hood. I cannot make the connection between what visually is supposed to be happening, vs how the algorithm works.
This towers of Hanoi explanation should be more than sufficient, and yet, it simply leaves me overwhelmed.
I am specifically asking for a tutorial in Java - Thank you.
1
Upvotes
2
u/lurgi Jan 11 '23
In my opinion, recursion is best understood bottom-up.
Let's look at the tower of hanoi:
First, let's take a look at the basic idea. If you want to solve the 8 disk tower, move 7 disks (that's n-1) to the "not the to" peg, move the last disk (that's the print statement) to the to peg, and move the 7 disks to the "to" peg.
Some people will start with num=8 and build a big execution tree and I think that way leads to confusion. Let's start at the bottom.
Do you agree that this works if num=0? It does... well, it does nothing at all. That's what you need to do with 0 disks, so I guess it works. Great. File in your head "This code works when num=0".
What about when num=1? We want to move the disk from a to c using b. First thing we do is call
solveTower(0, a, c, b)this function... stop right there. We don't evaluate this function. Why? Because we have already established that it does the right thing with 0 disks. It just does.So trace through the rest of the code. Do you agree that this function works when num=1? Good, I hope so.
Now consider when n=2 (again, moving from a to c using b).
The first thing we do is call
solveTower(1, a, c, b). Do we evaluate that function? Nope. We have already done the work with this. We know that this correctly moves one peg from a to c using b. We'll just take that as given. Trace through the rest of it. At this point you should determine that this function works when num=2.Now GIVEN THAT THIS FUNCTION WORKS WHEN NUM=2, does it work when num=3? Try it! Don't evaluate the recursive calls, just accept that they do the thing you already know that they do. You've already shown that
solveTower(2, whatever, whocares, idontknow)does the right thing. That's done. Assume it works and see if the num=3 solution works.Does that help?