in reply to
Re: Worst thing you ever made with Perl
in thread Worst thing you ever made with Perl
And now, the re-write:
use strict;
use warnings;
use CGI qw(header param);
use HTML::Template;
my @solution;
my $tmpl = HTML::Template->new(filehandle => \*DATA);
if (param('go')) {
my $discs = param('discs');
$discs = 1 if $discs < 1 or $discs > 15;
hanoi($discs,'A','B','C');
$tmpl->param(
solution => \@solution,
discs => $discs,
);
}
print header, $tmpl->output;
# original algorithm learned from Brenda Parker
sub hanoi {
my ($number, $from, $to, $aux) = @_;
if ($number == 1) {
push @solution, {step => "Move 1 from $from to $to"};
}
elsif ($number != 0) {
hanoi($number-1,$from,$aux,$to);
push @solution, {step => "Move $number from $from to $to"};
hanoi($number-1,$aux,$to,$from);
}
}
__DATA__
<html>
<head>
<title>Towers of Hanoi</title>
</head>
<body>
<form>
<p>
Enter number of discs desired (15 is MAX):
<input type="text" name="discs" size="2" />
</p>
<input type="submit" name="go" value="Solve" />
</form>
<tmpl_if solution>
<hr/>
Solving for <tmpl_var discs> discs:
<ol>
<tmpl_loop solution>
<li><tmpl_var step></li>
</tmpl_loop>
</ol>
</tmpl_if>
</body>
</html>