Hanoi Tower Counter

I wrote the code for the Towers Of Hanoi game. I do not know how to implement a counter for this program, how many times it was executed. Any help would be greatly appreciated.

public class MainClass {
  public static void main(String[] args) {
    int nDisks = 3;
    doTowers(nDisks, 'A', 'B', 'C');
  }

  public static void doTowers(int topN, char from, char inter, char to) {
    if (topN == 1){
      System.out.println("Disk 1 from " + from + " to " + to);
    }else {
      doTowers(topN - 1, from, to, inter);
      System.out.println("Disk " + topN + " from " + from + " to " + to);
      doTowers(topN - 1, inter, from, to);
    }
  }
}
+3
source share
1 answer

Change the return type doTowersfrom voidto intand set the return value to:

  • if topN == 1, return 1;
  • else returns the sum of two doTowers()plus 1.

The logic is similar to the problem algorithm. Have fun figuring it out!

You can also use a static global variable, but this may be a bad programming style.

+10
source

All Articles