Article...

Senin, 02 Juni 2008

Tower Of Hanoi

(*
http://en.wikipedia.org/wiki/Tower_of_Hanoi
http://www.cut-the-knot.org/recurrence/hanoi.shtml
Recurrence: T(h) = 2T(h-1) + 1 = 2**h - 1 --> O(2**h)
*)

program Hanoi_Tower;
// number of disks
var nd: integer;

(** Hanoi.
*
* A game invented by the French mathematician Edouard Lucas in 1883.
*
* 1. Move the top N-1 disks from Src to Aux (using Dst as an intermediary peg)
* 2. Move the bottom disk from Src to Dst
* 3. Move N-1 disks from Aux to Dst (using Src as an intermediary peg)
*
* @param n number of disks.
* @param from source peg.
* @param to_ destination peg.
* @param by intermediary peg.
*)
procedure Hanoi(n: integer; from, to_, by: char);
begin
if (n=1) then
writeln('Move the plate from ', from, ' to ', to_)
else begin
Hanoi(n-1, from, by, to_);
Hanoi(1, from, to_, by);
Hanoi(n-1, by, to_, from);
end;
end;

begin
write ( 'Enter number of disks: ' );
readln ( nd );
Hanoi (nd,'A','B','C')
end.

My Headlines