Algoritmes

  1. Towers of Hanoi[NEW]

Towers of Hanoi[NEW]

From: "John Bester" <jbester@ilink.nis.za>

The towers of hanoi is based on a very simple algorithm. I'll give you the algorithm and you can implement it.


type
  THanoiBin = 0..2;
  THanoiLevel = 0..9;
 

procedure MoveDisc(FromPin, ToPin : THanoiPin; Level : THanoiLevel);
//  This one you have to implement yourself. It moves 1 disc from a pin to another.
//  The disc to be moved must be on top (No discs above it)
You can represent the 3 towers in any way you want. 3 Stacks might probably the easiest. In this way MoveDisc will become MoveTopDisc and will move the disc on the top of the FromPin to ToPin and MoveTower will take a pointer to the base of a stack in stead of a level. Or you can simply use three arrays [THanoiLevel] of boolean in which case true means that the disc with the particular size depicted by THanoiLevel is on the tower.
procedure MoveTower(FromPin, ToPin : THanoiPin; Level : THanoiLevel);
begin
   if HanoiLevel <= High(THanoiLevel) then
   begin
       MoveTower(FromPin,  3 - FromPin - ToPin,  Level + 1);
       MoveDisc(FromPin, ToPin, Level);
       MoveTower(3 - FromPin - ToPin, ToPin,  Level + 1);
   end;
end;
To move the entire tower, you call MoveTower with the following as follows:
MoveTower(0, 1, Low(THanoiLevel));


Please email me and tell me if you liked this page.

This page has been created with