How to resolve the algorithm Towers of Hanoi step by step in the Pascal programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Towers of Hanoi step by step in the Pascal programming language

Table of Contents

Problem Statement

Solve the   Towers of Hanoi   problem with recursion.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Towers of Hanoi step by step in the Pascal programming language

Source code in the pascal programming language

program Hanoi;
type
  TPole = (tpLeft, tpCenter, tpRight);
const
  strPole:array[TPole] of string[6]=('left','center','right');

 procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole);
 begin
  if Ndisks >0 then begin
     MoveStack(Ndisks - 1, Origin,Auxiliary, Destination );
     Writeln('Move disk ',Ndisks ,' from ',strPole[Origin],' to ',strPole[Destination]);
     MoveStack(Ndisks - 1, Auxiliary, Destination, origin);
  end;
 end;

begin
 MoveStack(4,tpLeft,tpCenter,tpRight);
end.

program Hanoi;
type
  TPole = (tpLeft, tpCenter, tpRight);
const
  strPole:array[TPole] of string[6]=('left','center','right');

 procedure MoveOneDisk(const DiskNum:integer; const Origin,Destination:TPole);
 begin
  Writeln('Move disk ',DiskNum,' from ',strPole[Origin],' to ',strPole[Destination]);
 end;

 procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole);
 begin
  if Ndisks =1 then
       MoveOneDisk(1,origin,Destination)
  else begin
       MoveStack(Ndisks - 1, Origin,Auxiliary, Destination );
       MoveOneDisk(Ndisks,origin,Destination);
       MoveStack(Ndisks - 1, Auxiliary, Destination, origin);
  end;
 end;

begin
 MoveStack(4,tpLeft,tpCenter,tpRight);
end.

  

You may also check:How to resolve the algorithm Symmetric difference step by step in the Groovy programming language
You may also check:How to resolve the algorithm GSTrans string conversion step by step in the Julia programming language
You may also check:How to resolve the algorithm Read entire file step by step in the Crystal programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the TSE SAL programming language
You may also check:How to resolve the algorithm Chinese remainder theorem step by step in the zkl programming language