I have a recursive Tower of Hanoi program but don't know how to include the count variable. Could you tell me how?
Main.java
import java.io.*;
import java.util.List;
public class Main {
//int count = 0;
/**There is a stack of N disks on the first of three poles (call
them A, B and C) and your job is to move the disks from pole A to pole B without
ever putting a larger disk on top of a smaller disk.*/
public static void main(String[] args) {
System.out.println("Tower of Hanoi");
System.out.println("Program by Quang Pham");
playHanoi (3,"A","B","C");
System.out.println("All done.");
System.out.println("Took a total of n" + /*count*/ " moves.");
}
//move n disks from position "from" to "to" via "other"
private static void playHanoi( int n, String from , String other, String to) {
if (n == 0)
return;
if (n > 0)
playHanoi(n-1, from, to, other);
System.out.printf(/*"%d." +*/ "Move disk" + n + "from pole %s to pole %s \n ", /*count*/ from, to);
playHanoi(n-1, other, from, to);
}
/*int count++;*/
}
Any help with this problem would be greatly appreciated. Yours truly, Quang Pham
The code above has been modified to give the count for the Tower of hanoi problem.
import java.io.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
int count=playHanoi (3,"A","B","C");
System.out.println("Took a total of n" + count+ " moves.");
}
private static int playHanoi( int n, String from , String other, String to)
{ int count=1;
if (n == 0)
return;
else if(n==1)
{
System.out.println("move disk "+n+" from
rod "+from+" to rod "+to);
return
count;
}
else{
count+= playHanoi(n-1, from, to, other);
System.out.printf(/*"%d." +*/ "Move disk" + n + "from pole %s to pole %s \n ", /*count*/ from, to);
count+=playHanoi(n-1, other, from, to);
}
return count;
}
}
Get Answers For Free
Most questions answered within 1 hours.