defmodule Kata do
def digital_root(n) do
n |> Integer.digits() |> Enum.reduce(0, &Kernel. /2)
end
end
n = 1253
CodePudding user response:
You can use a multi clause function for this: in the first one, return n
unchanged if it's a single digit. Otherwise, compute the sum of digits (like you've already figured out) and recursively call the function on it again. Also, your reduce can be replaced with Enum.sum/1
.
defmodule Kata do
def digital_root(n) when n < 10, do: n
def digital_root(n) do
n |> Integer.digits() |> Enum.sum() |> digital_root()
end
end
Test:
iex(1)> Kata.digital_root(0)
0
iex(2)> Kata.digital_root(1)
1
iex(3)> Kata.digital_root(9)
9
iex(4)> Kata.digital_root(91)
1
iex(5)> Kata.digital_root(912)
3
iex(6)> Kata.digital_root(9123)
6
iex(7)> Kata.digital_root(1253)
2
CodePudding user response:
def digit_sum(number) when number < 10, do: number
def digit_sum(number) when is_integer(number) do
digit_sum(
for digit <- Integer.digits(number), reduce: 0 do
acc -> acc digit
end
)
end
I like Dogbert's better.