
Problem Description
In a monastery in Benares India there are three diamond
towers holding 64 disks made of gold. The disks are each of a different
size and have holes in the middle so that they slide over the towers
and sit in a stack. When they started, 1500 years ago, all 64 disks
were all on the first tower arranged with the largest on the bottom and the
smallest on the top. The monks' job is to move all of the disks to the
third tower following these three rules:
1. Each disk sits over a tower except when it is being moved.
2. No disk may ever rest on a smaller disk.
3. Only one disk at a time may be moved.
The monks are very good at this after all this time and can move about 1 disk
per second. When they complete their task, THE WORLD WILL END! The
question is, how much time do we have left?
Techniques & Background
Here is version 2 of the Towers problem. Version 2 extends the code
developed in version 1 by knowing which moves must be made in what order to
solve the problem Version 3, which adds graphics code to show
solutions or allows the user to solve the puzzle by dragging disks from tower to
tower, will be presented next time. If you haven't studied Towers1,
and are interested in understanding the solution, please do so first.
In version 2, we added a TTowers object to hold the towers and the
disks. Right now, they are just numbers, you can think of the disk number
a its diameter. When we get to the graphics version we will expand this
idea (TTowers will be contain array of TPeg objects and TPeg will contain
an array of TDisk objects). Here's the definition for now:
TTowers = class(Tobject)
Peg:array[1..3, 1.. maxdisks] of integer;
NbrDisks:array[1..3] of integer; {current nbr of disks on each peg}
procedure SetDisks(NewNbrDisks:integer);
{initialize ttowers with a number of disks}
function MoveOne(Frompeg, topeg:integer):integer; {return disk nbr of disk moved}
end;
The only slightly tricky part is in the MoveOne function. It is called
with FromPeg and ToPeg parameters so we must decide which peg is on top of
FromPeg and move that number to the next disk position on ToPeg. The xth
disk of FromPeg would be referenced as Peg[FromPeg, x]. so the top disk
of FromPeg can be referenced by Peg[FromPeg, NbrDisks[FromPeg]].
If you can follow that, then you can understand the rest of MoveOne.
Running/Exploring the Program