Implement the recursive Towers of Hanoi function given below (from the lecture n
ID: 672506 • Letter: I
Question
Implement the recursive Towers of Hanoi function given below (from the lecture notes). Develop a main program that allows the user to enter any number of disks to solve. Modify function towers so that all the print statements arc disabled (i.e.. comment them out). There needs to be a statement after if(numDisks ...), so replace that with just numDisks = numDisks. (The compiler will actually remove this pointless statement.) Modify the main program so that "Starting towers ..." is displayed right before the function is called, and "Finished towers" when completed (right after the function call). Run your program using this new version of the function (that does not display the moves) to determine how long it takes to complete for the following number of disks: Use your smart phone to determine each execution time to the nearest second.Explanation / Answer
import java.util.*;
/* Class TowerOfHanoiUsingStacks */
public class TowerOfHanoiUsingStacks
{
public static int N;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<Integer>();
tower[2] = new Stack<Integer>();
tower[3] = new Stack<Integer>();
/* Accepting number of disks */
System.out.println("Enter number of disks");
int num = scan.nextInt();
N = num;
toh(num);
}
/* Function to push disks into stack */
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
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(" ");
}