note
graq
First all, apologies for ruining some nice code. I have added a print statement and 4 comment points (A .. D).
<code>
#!/usr/bin/perl -w
use strict;
use warnings;
my %piles = (A => [reverse 1..3], B => [], C => []);
dumpPiles ();
hanoi (scalar @{$piles{A}}, keys %piles); #A
sub hanoi {
my ($n, $start, $end, $extra, $recursion) = @_;
print "Hanoi: Disk $n\n";
if ($n == 1) { #B
report ($start, $end, $recursion);
} else {
hanoi($n-1, $start, $extra, $end); #C
report ($start, $end, $recursion);
hanoi($n-1, $extra, $end, $start); #D
}
}
sub report {
my ($start, $end) = @_;
my $disk = pop @{$piles{$start}};
print "Moved disk $disk from $start to $end.\n";
push @{$piles{$end}}, $disk;
dumpPiles ();
}
sub dumpPiles {
for my $pile (sort keys %piles) {
print "$pile: @{$piles{$pile}}\n";
}
}
</code>
<p>The first hanoi call happens at point A, where the first argument (which disk to move) is equal the number of discs on pile A; namely '3'. We then move into the <c>hanoi</c> iterative method where the logical statement at B is false and we move to point C.</p>
<p>At point C we call <c>hanoi</c> again (note we have not called <c>report</c> yet, but the first argument has been decremented to '2'. This means we arrive at point B for the second time and the logical statement is still false.</p>
<p>We arrive at point C again, calling <c>hanoi</c> on disk number 1. Now the statement at B is true and the iterations begin to unravel.</p>
<p>Perhaps, together with the additional <c>print</c> statement in the code, this will help to explain things?</p>
<div class="pmsig"><div class="pmsig-79379">
<p>-=( <a href="http://www.graq.co.uk">Graq</a> )=-</p>
</div></div>
648942
648946