wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes recursion find number of times int appears in array... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "recursion find number of times int appears in array..." Watch "recursion find number of times int appears in array..." New topic
Author

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

Johnny Steele
Greenhorn

Joined: Nov 12, 2010
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

el Duderino
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Why do you want to solve this problem with recursion?


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Johnny Steele
Greenhorn

Joined: Nov 12, 2010
Posts: 12
my assignment requires it to be witten using recursion.
anirudh jagithyala
Ranch Hand

Joined: Dec 07, 2010
Posts: 41
Hey Johnny,

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



Johnny Steele
Greenhorn

Joined: Nov 12, 2010
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

Joined: Apr 06, 2010
Posts: 4343
    
    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

Joined: Nov 19, 2001
Posts: 173

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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: recursion find number of times int appears in array...
 
Similar Threads
find word occurence in string
Recent interview question - Find a pair in array whose sum is x.
Passing Vector elements to an array
Recursive Problem.
problem with recurssion