The technique is to use recursion. Maybe it is clearer if we get the code to actually move the "rings" and show the state of the piles after each move? Consider:
#!/usr/bin/perl -w
use strict;
use warnings;
my %piles = (A => [reverse 1..3], B => [], C => []);
dumpPiles ();
hanoi (scalar @{$piles{A}}, keys %piles);
sub hanoi {
my ($n, $start, $end, $extra) = @_;
if ($n == 1) {
report ($start, $end);
} else {
hanoi($n-1, $start, $extra, $end);
report ($start, $end);
hanoi($n-1, $extra, $end, $start);
}
}
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";
}
}
Prints:
A: 3 2 1
B:
C:
Moved disk 1 from A to C.
A: 3 2
B:
C: 1
Moved disk 2 from A to B.
A: 3
B: 2
C: 1
Moved disk 1 from C to B.
A: 3
B: 2 1
C:
Moved disk 3 from A to C.
A:
B: 2 1
C: 3
Moved disk 1 from B to A.
A: 1
B: 2
C: 3
Moved disk 2 from B to C.
A: 1
B:
C: 3 2
Moved disk 1 from A to C.
A:
B:
C: 3 2 1
Perl is environmentally friendly - it saves trees
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.