Recursive functions: Casting out Nines (in Bash)

Thu 05 April 2012
By mute

Someone asked how to implement an algorithm where you add the digits in a number, until you have a single digit left. For example: 1234 10 1

The first given solution used a loop. He asked if it could be done recursively. The second solution used recursion, but still a loop. Thankfully, by the advice of Riviera in irc://irc.freenode.org/#bash I had read some of "The Little Schemer" by Daniel P. Friedman.

My solution, in bash:

cast() { if ((${#1}>1)); then cast "$((${1:0:1}+${1:1:1}))${1:2}"; else echo $1; fi; }

It operates a bit different since it adds the first two digits and goes again, but with same result: 1234 334 64 10

I wondered if that would affect the output but I read Casting out nines on wikipedia and such and it seems solid.

:)

Comments