exercism/elixir/pascals-triangle/lib/pascals_triangle.ex

20 lines
567 B
Elixir

defmodule PascalsTriangle do
@doc """
Calculates the rows of a pascal triangle
with the given height
"""
@spec rows(integer) :: [[integer]]
def rows(num) do
1..num
|> Enum.reduce([[]], fn _, triangle -> [next(hd(triangle)) | triangle] end)
|> Enum.take(num)
|> Enum.reverse
end
defp next(from, acc \\ [])
defp next([], _acc), do: [1]
defp next([1], _acc), do: [1, 1]
defp next([one, two | []], acc), do: [1 | Enum.reverse([1, one + two | acc])]
defp next([one, two | rest], acc), do: next([two | rest], [one + two | acc])
end