My task was to add a bunch of print statements to display the the complete output of Tower of Hanoi to see and understand what it is doing behind the scenes, instead of just giving you the final result.
class TowersApp {
static int nDisks = 3;
public static void main(String[] args) {
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to) {
int i = 0;
if(topN==1) {
System.out.println("Enter (" + topN + " disk): " + "s=" + from + ", i=" + inter + ", d=" + to);
System.out.println("Base case: move disk " + topN + " from " + from + " to "+ to);
System.out.println("Return (" + topN + " disk)"); }
else {
System.out.println("Enter (" + topN + " disks): " + "s=" + from + ", i=" + inter + ", d=" + to);
doTowers(topN-1, from, to, inter);
System.out.println("Move bottom disk " + topN +
" from " + from + " to "+ to);
doTowers(topN-1, inter, from, to);
System.out.println("Return (" + topN + " disks)");
}
}
}
Here's what I have as my output. The only thing I am missing is indentation. I need to have 1 tab for the first level of recursion, 2 tabs for second level of recursion and so on... Here's what I mean:
Current Output:
Enter (3 disks): s=A, i=B, d=C
Enter (2 disks): s=A, i=C, d=B
Enter (1 disk): s=A, i=B, d=C
Base case: move disk 1 from A to C
Return (1 disk)
Move bottom disk 2 from A to B
Enter (1 disk): s=C, i=A, d=B
Base case: move disk 1 from C to B
Return (1 disk)
Return (2 disks)
Move bottom disk 3 from A to C
Enter (2 disks): s=B, i=A, d=C
Enter (1 disk): s=B, i=C, d=A
Base case: move disk 1 from B to A
Return (1 disk)
Move bottom disk 2 from B to C
Enter (1 disk): s=A, i=B, d=C
Base case: move disk 1 from A to C
Return (1 disk)
Return (2 disks)
Return (3 disks)
Desired Output:
Enter (3 disks): s=A, i=B, d=C
Enter (2 disks): s=A, i=C, d=B
Enter (1 disk): s=A, i=B, d=C
Base case: move disk 1 from A to C
Return (1 disk)
Move bottom disk 2 from A to B
Enter (1 disk): s=C, i=A, d=B
...................................
Would I need some sort of counter to "count" how many times I've gone into the function? But then, is that even possible with recursion? Perhaps I am over analyzing when there's a much simpler solution to this problem?