• Post Reply Bookmark Topic Watch Topic
  • New Topic

Counting values in recursivity: Should I use static value? Is the method inside, an instance?  RSS feed

 
Josh Borg
Ranch Hand
Posts: 37
Chrome Eclipse IDE Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In recursivity, there's anyway to keep some value for all the internal called recursive methods?


I am iterating a String inside some method, when I find an specific character I send it inside the same method by recursivity and return only when it finds other character of finalization. The problem is that I need that count of iterations, did inside this methods for the superior method in the hierarchy, I am sending it with the return, but, I think it's not elegant..

Can I use static values for it (I add count inside, and when it goes to the superior method it keeps this value)?
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can declare static field inside the class that contains recursive call and increment it each time you make a call to recursive method. Or, you can use accumulator as argument of your method and increment it each time recursive call is made. Something like:

Note that this recursive method returns depth as a result. If your recursive method returns some other value, you would just change depth to be a reference of a type you define, say:
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a knee‑jerk reaction to being asked whether something should be static, which is no.
There are reasons why something should be static, like being shared between all instances, available without creating an instance, etc. But I cannot see that applying to recursion. My first question about recursion would be: why isn’t it a method‑local variable?
Why not create a class which encapsulates the recursive values and the iteration count. Then you can pass and return that reference, and increment its counter. Let’s try that for a Fibonacci number, using the classic exponential complexity version:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!