how can count recursion function calls in java

Z

ziki

Hi guys,
I have a little question:
I have recursion function in my program (java program) , How can I
count the recursion calls that this function has made.

thanks in advance,
 
B

Boudewijn Dijkstra

ziki said:
Hi guys,
Hi.

I have a little question:
I have recursion function in my program (java program) , How can I
count the recursion calls that this function has made.

If the recursive algorithm is ever only executed by one thread, you can
increment a static variable in the enclosing class. Otherwise you'd have to
set up counts for each thread using ThreadLocal. Don't forget to reset the
counter when the recursion ends.
 
R

R.F. Pels

ziki said:
I have recursion function in my program (java program) , How can I
count the recursion calls that this function has made.

Homework???

public void recurse(int depth)
{
++depth;
if (depth < 10)
{
recurse(depth);
}
}
 
G

Gordon Beaton

If the recursive algorithm is ever only executed by one thread, you
can increment a static variable in the enclosing class. Otherwise
you'd have to set up counts for each thread using ThreadLocal.

In order to avoid threading issues and the need to reset the state
afterwards, I'd rather suggest using an accumulator (a common idiom
with recursion):

1. if the method doesn't already have something to return, keep track
of and return the depth with a primitive:

int recursiveMethod(int foo, int depth) {
if (isBaseCase(foo)) {
return depth;
}
else {
return recursiveMethod(int foo, depth+1);
}
}

2. if the method already uses the return value for something useful,
pass an object instead:

MyData recursiveMethod(int foo, Depth d) {
if (isBaseCase(foo)) {
return baseValue;
}
else {
return recursiveMethod(foo, d.increment());
}
}

You won't have to change any of the code that calls your function if
you use a wrapper:

MyData myFunction(int foo) {
Depth d = new Depth(0);
MyData r = myFunctionHelper(foo, d);
System.out.println("Depth was " + d.getDepth());
return r;
}

/gordon
 
O

Oliver Wong

R.F. Pels said:
Homework???

public void recurse(int depth)
{
++depth;
if (depth < 10)
{
recurse(depth);
}
}

Would have been funnier (to me, anyway) if you had written:

homework?"Figure it out yourself.":"public void recurse(int
depth){++depth;if (depth < 10)recurse(depth);}"

- Oliver
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top