pascals_triangle

This commit is contained in:
2024-07-07 00:41:15 -04:00
parent 44ca0cb19b
commit 58eac331ab
10 changed files with 376 additions and 0 deletions

View 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