Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Recursion Confusion

by Athanasius (Canon)
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?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2015-10-08 23:38 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (232 votes), past polls