Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Recursion Confusion

by Athanasius (Monsignor)
on Apr 27, 2013 at 06:43 UTC ( #1030931=note: print w/ replies, xml ) Need Help??


in reply to Recursion Confusion

When hanoi is called with $n > 1, the code in the else clause runs as follows:

  1. first recursive call with $n - 1
  2. The print statement you say “does not make sense”
  3. second recursive call with $n - 1

Update: My initial explanation with $n == 3 was wrong. Simpler to let $n == 2:

So with $n initially set at 2, (1) is executed. It recursively calls hanoi with $n == 1. At this point the if clause executes, and the function returns. Next, (2) produces the output that is confusing you. Then (3) produces another recursion; when this returns, the initial call to hanoi also returns, and the function is complete.

(Where I got confused earlier:) For each recursive call to hanoi where $n > 2, an additional else clause comes into play, adding its own print statement to the output.

Perhaps this helps: Every output statement where $n == 1 is written by the print statement in the if clause. Every other output statement (where $n > 1) is written by the print statement sandwiched between the two recursive calls in the else clause.

Clear now? ;-)

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


Comment on Re: Recursion Confusion
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2014-09-02 01:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (18 votes), past polls