HANOI TOWERS


We have 3 sticks ‘a’, ‘b’ and ‘c’. On the ‘a’ stick there are disks of different sizes so that the largest is at the bottom and the smallest at the top. The sticks ‘b’ and ‘c’ are empty. The task is to transfer the disks from the ‘a’ to ‘c’ stick by means of the ‘b’ auxiliary stick, but so that the smaller one is never covered by the larger one.

  PASCAL

The HANOI procedure displays the numbers of the poles: from which to which the disc should be moved. Calling up the function: HANOI (1, 2, 3, n) / 1, 2, 3 are pole numbers, n - number of discs

 program Hanoi;
 uses crt;
 procedure Hanoi(a,b,c,n :integer);
 begin
   if n=1 then writeln(a,', ',b)
  else
  begin
   Hanoi(a,c,b,n-1);
   writeln(a,', ',b);
   Hanoi(c,b,a,n-1);
  end;
 end;
 {*** MAIN ***}
 BEGIN
 ClrScr;
  Hanoi(1,2,3,3);
 readln;
 END.

 Results for 3 sticks: hanoi(1,2,3,3)


  C++

The HANOI procedure displays the numbers of the poles: from which to which the disc should be moved. Calling up the function: HANOI (1, 2, 3, n) / 1, 2, 3 are pole numbers, n - number of discs

 #include <iostream>
 using namespace std;
 void Hanoi(int a,int b,int c,int n)
 {
  if (n==1) cout<<a<<" "<<b;
 else
  {
  Hanoi(a,c,b,n-1);
  cout<<a<<" "<<b;
  Hanoi(c,b,a,n-1);
  }
 }
 //*** MAIN ***
 main()
 {
  Hanoi(1,2,3,3);
 return 0;
 }

  Results for 3 sticks: hanoi(1,2,3,3)


  PYTHON

The HANOI procedure displays the numbers of the poles: from which to which the disc should be moved. Calling up the function: HANOI (1, 2, 3, n) / 1, 2, 3 are pole numbers, n - number of discs

  Results for 3 sticks: hanoi(1,2,3,3)