How do I write a Tower of Hanoi program in Java to move 5 el
How do I write a Tower of Hanoi program in Java to move 5 elements and show how many steps it took to move them?
Solution
package cust;
import java.util.Stack;
public class TowerOfHanoi {
public static int N = 5;
public static int count = 0;
/* Creating Stack array which represents towers */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args) {
tower[1] = new Stack<Integer>();
tower[2] = new Stack<Integer>();
tower[3] = new Stack<Integer>();
hanoi(N);
System.out.println(\"Number of moves : \" + count);
}
public static void hanoi(int n) {
for (int d = n; d > 0; d--) { // push larger disk below the smaller ones
tower[1].push(d);
}
display();
move(n, 1, 2, 3);
}
public static void move(int n, int a, int b, int c) {
if (n > 0) {
move(n - 1, a, c, b);// /* Recursive call to move disks */
count++;
int d = tower[a].pop();
tower[c].push(d);
display();
move(n - 1, b, a, c);
//count--;
}
}
public static void display() {
System.out.println(\" A | B | C\");
System.out.println(\"---------------\");
for (int i = N - 1; i >= 0; i--) {
String d1 = \" \", d2 = \" \", d3 = \" \";
try {
d1 = String.valueOf(tower[1].get(i));
} catch (Exception e) {
}
try {
d2 = String.valueOf(tower[2].get(i));
} catch (Exception e) {
}
try {
d3 = String.valueOf(tower[3].get(i));
} catch (Exception e) {
}
System.out.println(\" \" + d1 + \" | \" + d2 + \" | \" + d3);
}
System.out.println(\"\ \");
}
}

