pascals_triangle
This commit is contained in:
19
elixir/pascals-triangle/lib/pascals_triangle.ex
Normal file
19
elixir/pascals-triangle/lib/pascals_triangle.ex
Normal file
@@ -0,0 +1,19 @@
|
||||
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
|
||||
Reference in New Issue
Block a user