Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# recursion find number of times int appears in array...

Johnny Steele
Greenhorn
Posts: 12
Hi,

Who loves recursion?!?!?!?!

So, given an array of ints I need to recursively find the number of times a particular integer appears in that array. Like so:

This code is creating a huge stackOverFlow error when I unit test it. I am at a loss. I am allowed to use private helper methods although I am a bit confused as to how that would help in general or particular to this case. Regardless, any suggestions?

Thank you much

Wouter Oet
Saloon Keeper
Posts: 2700
Why do you want to solve this problem with recursion?

Johnny Steele
Greenhorn
Posts: 12
my assignment requires it to be witten using recursion.

anirudh jagithyala
Ranch Hand
Posts: 41
Hey Johnny,

Check out the below code.....This would work as far as i understood your requirement.

Johnny Steele
Greenhorn
Posts: 12
that seems to work!!! thank you very much!!! I did not think to use a for loop as in the past we've been told to avoid loops but not with this one.

thanks a lot!!!

Matthew Brown
Bartender
Posts: 4567
8
The reason your original version didn't work is because you kept calling the method with the same arguments. Which means you got into an infinite loop - and eventually the stack runs out of memory and falls over.

If you're using recursion, you've got to make sure that the recursion is guaranteed to end at some point. Anirudh's version works because the array is one element shorter every time the method is called, so eventually you hit a zero length and the recursion stops.

Carey Brown
Ranch Hand
Posts: 1480
18
Your problem is a linear problem, recursion tends to be used on tree structures. This code uses recursion to subdivide an array a-la binary search, thereby artificially treating the problem as a tree.