Home > Enterprise >  Is there any way I can count how many times a string recursive method runs in Java?
Is there any way I can count how many times a string recursive method runs in Java?

Time:10-30

This code checks if there are any more "B" characters left in the 2d array. Is there any way I can count how many times this recursive method calls itself?

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

CodePudding user response:

The simplest way is to use a static counter variable that you reset before calling the method.

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

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

CodePudding user response:

I have a love/hate relationship with static. It's abused far too often.

The concept of adding a "counter" to this method is causing a "side effect". The method is "doing a job", but it's also causing "something else" to happen. Good, bad, ugly? Not for me to say, but something you may want to keep in mind.

One approach might be to create a dedicated Counter class, which provides a means to "increment" a int value. You would then pass this into the method each time you call it...

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

This kind of approach overcomes the issue when you introduce multiple threads (calling the noMoreBs method) which would have an adverse effect if you used a static variable.

Then you would simply create an instance of Counter and pass it it

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

Another idea might be to use a "wrapper" class, which combined the concept of the counter with the the return value, then you would just return this "wrapper" class as a self contained unit of work

nb: you seem to be ignoring the result of subsequent calls to noMoreBs, so I'm not sure what it's trying to achieve here, but that's beyond the scope of the question

  • Related