Refer to the classwork on Tower of Hanoi Modify the program
Refer to the classwork on Tower of Hanoi. Modify the program to display the total number of disk movement at the end of the program. Also modify the program to display the disk numbers involved in the movement.
Create another class containing an iterative method for the Tower of Hanoi problem. provide a main method to test your class.
THIS IS THE CLASSWORK:
package recursion;
public class towerOfHanoi {
public static void main(String[] a) {
int num_of_disk=3;
int peg1=1;
int peg2=2;
int peg3=3;
SolveTower(num_of_disk, peg1, peg2, peg3);
}
public static void SolveTower(int n,int soursepeg, int desPeg, int tempPeg){
if(n==1){
System.out.println(soursepeg +\"--- >\"+ desPeg );
return;
}
SolveTower(n-1, soursepeg, tempPeg, desPeg);
System.out.println(soursepeg +\"--- >\"+ desPeg );
SolveTower(n-1, tempPeg, desPeg, soursepeg);
}
}
Solution
//just introduce a static variable called count
package recursion;
public class towerOfHanoi {
static int count=0;
public static void main(String[] a) {
int num_of_disk=3;
int peg1=1;
int peg2=2;
int peg3=3;
SolveTower(num_of_disk, peg1, peg2, peg3);
System.out.println(\"\ no of disk movements : \"+count);
}
public static void SolveTower(int n,int soursepeg, int desPeg, int tempPeg){
if(n==1){
System.out.println(soursepeg +\"--- >\"+ desPeg );
count++;
return;
}
SolveTower(n-1, soursepeg, tempPeg, desPeg);
System.out.println(soursepeg +\"--- >\"+ desPeg );
count++;
SolveTower(n-1, tempPeg, desPeg, soursepeg);
}
}

