Counter for Towers Of Hanoi

丶灬走出姿态 提交于 2020-01-03 18:59:16

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/10287847/counter-for-towers-of-hanoi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!