John Smith
John Smith

Reputation: 61

Counter for Towers Of Hanoi

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);
    }
  }
}

Upvotes: 3

Views: 1018

Answers (1)

zw324
zw324

Reputation: 27220

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.

Upvotes: 10

Related Questions