Replace recursive version with pattern-matching version of fizzbuzz
This commit is contained in:
parent
c91dc3b94e
commit
bcf3dd0ec4
|
@ -19,23 +19,11 @@ defmodule FizzBuzz do
|
|||
end
|
||||
end
|
||||
|
||||
defmodule RecursiveFizzBuzz do
|
||||
def upto(n) when n > 0, do: _upto(1, n, [])
|
||||
defmodule ElixirFizzbuzz do
|
||||
def upto(n) when n > 0, do: 1..n |> Enum.map(&fizzbuzz/1)
|
||||
|
||||
defp _upto(_current, 0, result), do: Enum.reverse result
|
||||
|
||||
defp _upto(current, left, result) do
|
||||
next_answer =
|
||||
cond do
|
||||
rem(current, 3) == 0 and rem(current, 5) == 0 ->
|
||||
"Fizzbuzz!"
|
||||
rem(current, 3) == 0 ->
|
||||
"Fizz"
|
||||
rem(current, 5) == 0 ->
|
||||
"Buzz"
|
||||
true ->
|
||||
current
|
||||
end
|
||||
_upto(current+1, left-1, [next_answer | result] )
|
||||
end
|
||||
def fizzbuzz(n) when rem(n, 3) == 0 and rem(n, 5) == 0, do: "Fizzbuzz!"
|
||||
def fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz"
|
||||
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
|
||||
def fizzbuzz(n) when n > 0, do: n
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue