WHAT IS TOWER OF HANOI?

The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
  • No larger disk may be placed on top of a smaller disk.

The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.

Source

In this code block i tried to make a mathematical game to show you using of stacks in Java. Tower of Hanoi is the most useful thing to learn Stack structure. If you have any questions please comment.

ALGORITHM OF TOWER OF HANOI IN JAVA

import java.util.Scanner; import java.util.Stack; //www.rojhat.com public class main { public static void playStack(Stack A,Stack B){// This method is used for moving the disks. int n1=0; int n2=0;

if (!A.isEmpty()) { // if first tower is not empty for(Integer i:A){n1=i;}//find the last element to move.You can move just the last element.

for(Integer i:B){n2=i;}//find the last element to compare if (n1 X, Stack Y,Stack Z){

System.out.print("Tower X: "); for(Integer i:X){ System.out.print(i+","); } System.out.print("Tower Y: "); for(Integer i:Y){ System.out.print(i+","); } System.out.print("Tower Z: "); for(Integer i:Z){ System.out.print(i+","); }

} public static void main(String[] args) {

Stack X = new Stack(); Stack Y = new Stack(); Stack Z = new Stack();

System.out.println("Write the size of disks:"); Scanner scanner= new Scanner(System.in); int disksize=scanner.nextInt();

for (int i = disksize; i>=1; i--) { X.push(i); }

String options="Stack-Selection\n" +"1)Move X-Y\n" + "2)Move Y-X\n" + "3)Move X-Z\n"+ "4)Move Z-X\n" +"5)Move Y-Z\n" +"6)Move Z-Y\n"; System.out.println(options);

printTower(X, Y, Z); while (true) { System.out.println("Choose a move:"); System.out.println(""); int select = scanner.nextInt(); if (select==1) { playStack(X, Y); // Move a disk from X to Y printTower(X, Y, Z);

} else if (select==2) { playStack(Y, X);Move a disk from Y to X printTower(X, Y, Z);

} else if (select==3) { playStack(X, Z); printTower(X, Y, Z); } else if (select==4) { playStack(Z, X); printTower(X, Y, Z); } else if (select==5) { playStack(Y, Z); printTower(X, Y, Z); } else if (select==6) { playStack(Z, Y); printTower(X, Y, Z); }

else{ System.out.println("Selection error choose between 1-6"); } } } }

Use this case to test the program:

  1. Set size to 3

  2. Move from 1 to 2

  3. Move from 1 to 2 (error)

  4. Move from 1 to 3