0

I am trying to count the number of times the method recurses during the life of the program. The code below gets the desired result, but uses global variables. Is there a way around this or a better way?

$count = 0
def AdditivePersistence(num)
  return 0 if num.to_s.length == 1  
  numarr = num.to_s.chars.map!(&:to_i)
  i = numarr.inject(&:+)
  $count+=1
    if i.to_s.length!=1
    AdditivePersistence(i)
    end
  $count
end
0

3 Answers 3

1

Since you want the total number of recursive calls during the lifetime of the program, a global variable in some form is the only way you can do it. You can either use an explicit global variable, as you have done, or a global variable in disguise, such as a singleton class, or a thread-local variable. I will not illustrate those here since they are inferior to plain global variables for this use case.

Sign up to request clarification or add additional context in comments.

Comments

0

You could take in an array with the first variable in the array being num and then the second being the count. then you just will do return [num, count]

Comments

0

Another option would be to update your method definition to accept the counter as an argument.

Using this approach, your method can just increment whatever counter value it receives and then pass the incremented value along in the recursive call.

def AdditivePersistence(num, counter)
  return 0 if num.to_s.length == 1  
  numarr = num.to_s.chars.map!(&:to_i)
  i = numarr.inject(&:+)
  counter +=1
    if i.to_s.length!=1
    AdditivePersistence(i, counter)
    end
  counter
end
# usage
AdditivePersistence(12, 0)

1 Comment

This is not equivalent to the OP's version. Your version counts the deepest level of recursion separately for each individual call to AdditivePersistence. The OP's version counts the running total of all recursive calls during the entire lifetime of the program. So, if I call your version twice with 1234 as an argument, it will return 2 both times, whereas the OP's version will return 2 the first time and 4 the second time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.