kernelthread.com

Perl (non-recursive)

The Towers of Hanoi as a non-recursive Perl script.

#! /usr/bin/perl # # The Towers Of Hanoi # Perl (non-recursive) # Copyright (C) 1998 Amit Singh. All Rights Reserved. # http://hanoi.kernelthread.com # # Tested under Perl 5.004_72 # ($#ARGV == 0) or die "usage: $0 N\n"; my $N = int($ARGV[0]); ($N > 0) or die "$0: illegal value for number of disks\n"; my @STACK = (); push(@STACK, $N, 1, 3, 0); while (@STACK) { $processed = pop(@STACK); $to = pop(@STACK); $from = pop(@STACK); $N = pop(@STACK); $left = 6 - $from - $to; if($processed == 0) { if ($N == 1) { print "\nmove $from --> $to [ disk #1 ]"; } else { push(@STACK, $N, $from, $to, 1, $N-1, $from, $left, 0); } } else { print "\nmove $from --> $to [ disk #$N ]"; push(@STACK, $N-1, $left, $to, 0); } } print "\n"; #__END__

Download

hanoi.npl