Reputation: 27
I'm trying to solve a Digital Root problem using Recursion. It seems to work for the first time around but not for the consecutive times. Here's what I want it to do:
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6
digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2
Here's what I got:
def digital_root(n)
arr = n.to_s.split("")
arr.size > 1 ? arr[0].to_i + digital_root(arr[1..-1].join).to_i : arr.join.to_i
end
Let me know how to make it work regardless of how many layers I need. Thanks in advance.
Upvotes: 2
Views: 54
Reputation: 2409
In your code, the function processes only 1 digits in 1 call. (4
for digital_root(493193)
)
Let's process 1 layer in 1 call and call next one (digital_root(29)
).
def digital_root(n)
arr = n.to_s.split("")
arr.size > 1 ? digital_root(arr.map(&:to_i).sum) : arr.join.to_i
end
And slightly better version.
def digital_root(n)
n < 10 ? n : digital_root(n.digits.sum)
end
Upvotes: 2