Forums Register Login

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

+Pie Number of slices to send: Send

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)?
+Pie Number of slices to send: Send
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:
+Pie Number of slices to send: Send
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:

When you have exhausted all possibilities, remember this: you haven't - Edison. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 799 times.
Similar Threads
Collection exercise Scrabble
SCJP: Threads Qs
Get values from a textarea
variables
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 04:06:52.