• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Johnny Steele
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you want to solve this problem with recursion?
 
Johnny Steele
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my assignment requires it to be witten using recursion.
 
anirudh jagithyala
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Johnny,

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



 
Johnny Steele
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 1389
16
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic