Supposing a recursive function, for instance:
public static int factorial(int n){
if(n==0){
return 1;
} else return n*factorial(n-1);
}
How can I know how many times has been called for each parameter and store them in a map
? (i.e: 10 times for n=5, 24 times for n=9 etc...)
EDIT:
Suppose the goal is to call it from a method like this, and it could be called many times within the program:
public Map<Integer, Integer> getTheNumberOfOccasionsItHasBeenCalled();
Basic solution for the case where you want to call the number of recursions for every possible input value (which in the case of factorial isn't that useful, but it could be in other cases):
static int thenumberoftimesiwascalled;
public static int factorial(int n){
thenumberoftimesiwascalled++;
if(n==0){
return 1;
} else return n*factorial(n-1);
}
...
Map<Integer,Integer> thenumberoftimeshewascalled = new HashMap<>();
for (int i=1;i+100;i++) {
// reset counter
thenumberoftimesiwascalled = 0;
// calculate
int result = factorial(i);
System.out.println("called " + thenumberoftimesiwascalled + " times for " + i);
// stash in Map
thenumberoftimeshewascalled.put(i,result);
}
Doing something useful with the map is left as an exercise, minimal version
static public Map<Integer, Integer> getNumberOfTimesCalled() {
return thenumberoftimeshewascalled;
}
Other interpretation, if you only want to count the number of times the function was called externally and not the number of recursions:
Map<Integer,Integer> externalcallspervalue = new HashMap<>();
// the actual function, renamed to hide avoid you having to change
// in all the places it was called:
private static int internalfactorial(int n){
if(n==0){
return 1;
} else return n*factorial(n-1);
}
// and a simple wrapper that does the accounting - and has the same name
// and signature of the original function.
public static int factorial(int n){
// do the accounting
Integer ntc = externalcallspervalue.get(i);
if (ntc==null) { // first time we see this value
ntc=1;
} else {
ntc += 1;
}
externalcallspervalue.put(i,ntc);
// and return the result by calling the hidden internal function
return internalfactorial(i);
}
Now
for (int i=1;i+100;i++) {
int result = factorial(i);
}
Will give you 1:1 2:1 3:1
as each value was called once.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments