| 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: 3786
|
|
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: 159
|
|
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.
|
 |
 |
|
|
subject: recursion find number of times int appears in array...
|
|
|