#!/usr/bin/perl
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# Copyright (C) 2008 Vino Fernando Crescini
# Towers of Hanoi
# hanoi(peg_init, peg_dest, peg_temp, n)
sub hanoi
{
if ($_[3] != 0)
{
# move n - 1 discs from peg_init to peg_temp using peg_dest as temp
hanoi($_[0], $_[2], $_[1], ($_[3] - 1));
# move nth disc from peg_init to peg_dest
print "move disc $_[3] from peg $_[0] to peg $_[1]\n";
# move n - 1 discs from peg_temp to peg_dest using peg_init as temp
hanoi($_[2], $_[1], $_[0], ($_[3] - 1));
}
}
$peg_init = "init";
$peg_dest = "dest";
$peg_temp = "temp";
if (($#ARGV != 0) && ($#ARGV != 3))
{
print "usage: hanoi.pl [ ]\n";
exit 1;
}
# is n a number?
if ($ARGV[0] !~ /^[0-9]+$/)
{
print "first argument must be a positive integer\n";
exit 2;
}
if ($#ARGV == 3)
{
$peg_init = $ARGV[1];
$peg_dest = $ARGV[2];
$peg_temp = $ARGV[3];
}
hanoi($peg_init, $peg_dest, $peg_temp, $ARGV[0]);
exit 0;