Last active
February 23, 2019 07:00
-
-
Save snewcomer/21c1eb2e6b00c60b57b636b195044557 to your computer and use it in GitHub Desktop.
Calculate binomial coefficient of one diagonal of pascal's triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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