Towers of Hanoi

According to a legend there are three toewrs in Hanoi. At the bgining of the time there were 64 discs on tower A. Discs were in order from the biggest to the smallest. Discs from tower A need to be moved to tower B using tower C when needed. Each day mnks can move only one disc. All the time discs need to be in order from the biggest to the smallest. According to the legend when monks move the last disc, the world will come o the end.

Enter number of discs (<12):



PHP code:
<?php
function Towers($n, $x,  $y, $z)
{
        if($n)
        {
                Towers($n-1, $x, $z, $y);
                print "move top $n disk from tower <b>$x</b> to top of tower <b>$y</b><br>";
                Towers($n-1, $z, $y, $x);
        }
}
	if(isset($Maxnumber)){
		$ok = true;
		if(strlen($Maxnumber)>2) 
		{
				print("<br><br><b>Number too big!</b><BR>");
				$ok = false;
		}
		else {
			for($i = 0; $i<strlen($Maxnumber);  $i++)
			{
				if(!($Maxnumber[$i]>='0' && $Maxnumber[$i]<='9')) { 
						print "<br><br><b>Incorrect number! (not digit)</b><BR>";
						$ok = false;
						break;
				}
			}
			if($Maxnumber>12){
				$ok = false;
			}
		}
		if($ok) {
			print"Discs are numbered from top (smallest) to bottom (biggest).<br><font color=\"red\">";
			$x = 'A';
			$y = 'B';
			$z = 'C';
			Towers($Maxnumber, $x,  $y, $z);
			print"</font></pre>";
		}
	}
	f();
?>


Back to main page