modify the program to display the disk numbers involved in the movement. Create
ID: 3926369 • Letter: M
Question
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 PROGRAM:
//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);
}
}
Explanation / Answer
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+" and "+desPeg+" are being swapped");
System.out.println(soursepeg +"--- >"+ desPeg );
count++;
return;
}
SolveTower(n-1, soursepeg, tempPeg, desPeg);
System.out.println(soursepeg+" and "+desPeg+" are being swapped");
System.out.println(soursepeg +"--- >"+ desPeg );
count++;
SolveTower(n-1, tempPeg, desPeg, soursepeg);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.