Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^3: Recursion Confusion

by rnewsham (Hermit)
on Apr 29, 2013 at 07:14 UTC ( #1031169=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Recursion Confusion
in thread Recursion Confusion

Don't worry recursion is a difficult thing to grasp at first. I have been using recursion for years and it still gives me a headache.

It sounds like your problem is understanding how you are getting the order of output that you are. You expect to see output in a order for example 1,2,3,4 but are seeing what you think is 1,3,4,2. This is a common trap with thinking about recursion. An easy way to get that code mixed up would be to expect the call I have commented as "hanoi 2" to be executed immediatly after the call to "hanoi 1". This is not the case at that point the sub hanoi is called so you will either hit the other condition in the if or call hanoi 1 again. The calls to hanoi 1 will continue until n==1 then that path ends and then the call hanoi 2 is made.

With most programming problems reducing the complexity to a small number of iterations can be the best way to visualise what is happening. However sometimes with recursion you need it to have more iterations to be able to see the pattern. Try increasing the number of disks in my example code, somewhere between five and ten should be enough. That should help you see the pattern of what the code is doing.


Comment on Re^3: Recursion Confusion

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1031169]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2014-07-30 10:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (230 votes), past polls