例如,將 的所有數字相加1253
,1 2 5 3
即11
。這是兩位數,所以再次將它們相加得到2
。剩下的最后一個數字是個位數。
這是我到目前為止所擁有的:
defmodule Kata do
def digital_root(n) do
n |> Integer.digits() |> Enum.reduce(0, &Kernel. /2)
end
end
n = 1253
uj5u.com熱心網友回復:
您可以為此使用多子句功能:在第一個中,n
如果它是單個數字,則回傳不變。否則,計算數字的總和(就像你已經弄清楚的那樣)并再次遞回呼叫它的函式。此外,您的 reduce 可以替換為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
測驗:
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
uj5u.com熱心網友回復:
只是為了好玩,這是一個不使用Integer.digits/2
or的版本,Enum
而是使用div/2
andrem/2
來計算每次迭代的最低有效位:
defmodule Kata do
# Function header
def digital_root(to_sum, acc \\ 0)
# Base case. All digits added, acc is a single digit
def digital_root(0, acc) when acc < 10, do: acc
# Finished a round. All digits added, acc is multiple digits. Sum again.
def digital_root(0, acc), do: digital_root(acc, 0)
# Split off the least significant digit, add it, and recurse
def digital_root(to_sum, acc) do
digit = rem(to_sum, 10)
next_to_sum = div(to_sum, 10)
digital_root(next_to_sum, acc digit)
end
end
輸出:
iex> Kata.digital_root(1523)
2
在基準測驗中,這個版本的速度是 dogbert 的兩倍,比 7stud 的答案快三倍。
Name ips average deviation median 99th %
adam 14.26 M 70.13 ns ±1898.51% 66.70 ns 83.30 ns
dogbert 7.08 M 141.28 ns ±14510.93% 125 ns 167 ns
sevenstud 4.83 M 206.98 ns ±15193.15% 167 ns 292 ns
Comparison:
adam 14.26 M
dogbert 7.08 M - 2.01x slower 71.14 ns
sevenstud 4.83 M - 2.95x slower 136.85 ns
Operating System: macOS
CPU Information: Apple M1 Pro
Number of Available Cores: 10
Available memory: 16 GB
Elixir 1.13.4
Erlang 24.3.4
uj5u.com熱心網友回復:
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
我更喜歡Dogbert。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490549.html