Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Last active February 23, 2019 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snewcomer/21c1eb2e6b00c60b57b636b195044557 to your computer and use it in GitHub Desktop.
Save snewcomer/21c1eb2e6b00c60b57b636b195044557 to your computer and use it in GitHub Desktop.
Calculate binomial coefficient of one diagonal of pascal's triangle
defmodule Easydiagonal do
def diagonal(n, p) do
{sum, _acc} = build_triangle(n, p)
sum
end
defp build_triangle(n, p) do
# [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], ...]
Stream.iterate({0, [1]}, fn {sum, last} ->
new_sum =
case Enum.at(last, p) do
nil -> sum
num -> sum + num
end
{new_sum, pascalit(last)}
end)
|> Enum.take(n + 2)
|> Enum.at(-1)
end
defp pascalit([1]), do: [1, 1]
defp pascalit(acc) do
result =
Stream.chunk(acc, 2, 1)
|> Enum.reduce([], fn [h, t], acc ->
[h + t | acc]
end)
[1] ++ result ++ [1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment