<?xml version="1.0" encoding="windows-1252"?>
<node id="400977" title="Re: Recursion: the Towers of Hanoi problem" created="2004-10-20 16:11:05" updated="2005-06-13 20:54:20">
<type id="11">
note</type>
<author id="387240">
terra incognita</author>
<data>
<field name="doctext">
Here is a modified version that will display a simple ASCII representation for those people like myself that think better in pictures.  &lt;br&gt;I am sure that this can be improved significantly.  &lt;br&gt;Comments on where I can improve this code and what practices I should stay away from are appreciated.  &lt;br&gt;This should work on both Windows and Solaris though the format may be a little off on Solaris.

&lt;code&gt;
#!/usr/local/bin/perl
use strict;

# Towers of Hanoi
# Perl version (5.8.0)
# Ported from Java

my $numdisks = 0;
my $count =0;
print "Number of disks? ";
chomp( $numdisks = &lt;STDIN&gt; );
clear ();
my $i;
my @polea;
my @poleb;
my @polec;
my $loop = 0;
my $string ;
while ($numdisks &gt; $loop++) {
	$string = $string ."x";
	push (@polea, $string);
	push (@poleb, "");
	push (@polec, "");
}
print "A\tB\tC\n";
for (my $len = 0 ;$len &lt;= ($numdisks -1); $len++) {
	print "$polea[$len]\t$poleb[$len]\t$polec[$len]\n";
}
sleep 2;
clear ();
movedisks( $numdisks, 'A', 'B', 'C' );

# SUB LAND 
sub clear {
	if ($^O eq "MSWin32") {
		system 'cls';
	}else{
		system 'clear';
	}
}

sub movedisks {
my( $num, $from, $to, $aux ) = @_;
	if( $num == 1 ) {
		paintdisks ($num, $to, $from);
	}else{
		movedisks( $num-1, $from, $aux, $to );
		paintdisks ($num, $to, $from);
		movedisks( $num-1, $aux, $to, $from );
	}
}

sub paintdisks {
	my( $num, $dest, $source) = @_;
	my $foo;

	if ($source eq "A") {
		$foo = $polea[0];
		shift @polea;
	}elsif ($source eq "B") {
		$foo = $poleb[0];
		shift @poleb;
	}else{
		$foo = $polec[0];
		shift @polec;
	}
	if ($dest eq "A") {
		unshift @polea, $foo;
	}elsif ($dest eq "B") {
		unshift @poleb, $foo;
	}else{
		unshift @polec, $foo;
	}
	print "A\tB\tC\n";
	for (my $len = 0 ;$len &lt;= ($numdisks -1); $len++) {
		print "$polea[$len]\t$poleb[$len]\t$polec[$len]\n";
	}
	sleep 2;
	clear ();
}
&lt;/code&gt;</field>
<field name="root_node">
400359</field>
<field name="parent_node">
400359</field>
</data>
</node>
