go ahead... be a heretic PerlMonks

Comment on

 Need Help??

Sometimes I find with recursion it helps to add some tracking to help visualise what path is being followed.

Hope this helps

```use warnings;
use strict;

my \$ndisks = 3;
hanoi( \$ndisks, 'A', 'C', 'B', 0 );

sub hanoi
{
my( \$n, \$start, \$end, \$extra, \$depth ) = @_;

print "\t"x\$depth . "n=\$n, start=\$start end=\$end extra=\$extra\
+n";

if( \$n == 1 )
{
print "\t"x\$depth . "Move disk #\$n from \$start to \$end
+\n";
}
else
{
\$depth++;
print "\t"x\$depth . "Calling hanoi 1\n";
hanoi( \$n-1, \$start, \$extra, \$end, \$depth);
print "\t"x\$depth . "Move disk #\$n from \$start to \$end
+\n";
print "\t"x\$depth . "Calling hanoi 2\n";
hanoi (\$n-1, \$extra, \$end, \$start, \$depth);
}
}

```n=3, start=A end=C extra=B
Calling hanoi 1
n=2, start=A end=B extra=C
Calling hanoi 1
n=1, start=A end=C extra=B
Move disk #1 from A to C
Move disk #2 from A to B
Calling hanoi 2
n=1, start=C end=B extra=A
Move disk #1 from C to B
Move disk #3 from A to C
Calling hanoi 2
n=2, start=B end=C extra=A
Calling hanoi 1
n=1, start=B end=A extra=C
Move disk #1 from B to A
Move disk #2 from B to C
Calling hanoi 2
n=1, start=A end=C extra=B
Move disk #1 from A to C

In reply to Re: Recursion Confusion by rnewsham
in thread Recursion Confusion by live4tech

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2017-06-27 11:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How many monitors do you use while coding?

Results (603 votes). Check out past polls.