繁体   English   中英

有什么方法可以计算字符串递归方法在 Java 中运行的次数?

[英]Is there any way I can count how many times a string recursive method runs in Java?

此代码检查二维数组中是否还有“B”字符。 有什么办法可以计算这个递归方法调用自身的次数吗?

  public static String[][] noMoreBs(String[][] a){
    randMover(a);
    adjacentCheck(a);

    for(int i = 0; i < a.length; i++){
      for(int j = 0; j < a[j].length; j++){
        if(a[i][j] == "B"){
          noMoreBs(a);
          return a;
        }
      }
    }
    return a;
  }

最简单的方法是使用在调用方法之前重置的静态计数器变量。

private static int count;
public static String[][] myMethod(String[][] a){
   ++count;
   // ...
}

// Call method:
count = 0;
myMethod(arr);

我对static有爱/恨的关系。 它被滥用得太频繁了。

向此方法添加“计数器”的概念会导致“副作用”。 该方法是“做一份工作”,但它也会导致“其他事情”发生。 好,坏,丑? 不是我要说的,而是您可能要记住的事情。

一种方法可能是创建一个专用的Counter类,它提供了一种“增加” int值的方法。 每次调用它时,你都会将它传递给方法......

public class Counter {
    private int value;
    
    public void increment() {
        value += 1;
    }
    
    public int getCount() {
        return value;
    }
}

public static String[][] noMoreBs(String[][] a, Counter counter) {
    counter.increment();
    randMover(a);
    adjacentCheck(a);

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[j].length; j++) {
            if ("B".equals(a[i][j])) {
                noMoreBs(a, counter);
                return a;
            }
        }
    }
    return a;
}

当您引入多个线程(调用noMoreBs方法)时,这种方法克服了这个问题,如果您使用static变量,这会产生不利影响。

然后您只需创建一个Counter实例并将其传递给它

Counter counter = new Counter();
String[][] results = noMoreBs(original, counter);
System.out.println(counter.getCount());

另一个想法可能是使用“包装器”类,它将计数器的概念与返回值结合起来,然后您只需将此“包装器”类作为自包含的工作单元返回

注意:您似乎忽略了对noMoreBs的后续调用的结果,所以我不确定它在这里试图实现什么,但这超出了问题的范围

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM