3

I have written a code for Towers Of Hanoi game. I don't know how to implement a counter for this program on how many times it ran. Any help will be much 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);
    }
  }
}
Mat
  • 202,337
  • 40
  • 393
  • 406
John Smith
  • 61
  • 1
  • 8

1 Answers1

10

Change the return type of doTowers from void to int, and set the return value to:

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

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

You could also use a static global variable, but that's arguably bad programming style.

zw324
  • 26,764
  • 16
  • 85
  • 118