Created
July 13, 2016 13:07
-
-
Save terakilobyte/b5408414fc6446f331c2265d8add7a29 to your computer and use it in GitHub Desktop.
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 PascalsTriangle do | |
@doc """ | |
Calculates the rows of a pascal triangle | |
with the given height | |
Calculated from the bottom up. | |
""" | |
@spec rows(integer) :: [[integer]] | |
def rows(0, acc), do: acc | |
def rows(num) do | |
num | |
|> do_pascal | |
end | |
defp do_pascal(num, acc \\ []) | |
defp do_pascal(0, acc), do: acc | |
defp do_pascal(num, acc) do | |
row = num - 1 | |
|> get_list_from_range | |
|> get_pascal(num - 1) | |
do_pascal(num - 1, [row | acc]) | |
end | |
defp get_list_from_range(n) do | |
Enum.into(0..n, []) | |
end | |
defp get_pascal(list, row) do | |
List.foldr(list, [], fn(x, acc) -> | |
[n_choose_k(row, x) | acc] | |
end) | |
end | |
@doc """ | |
Calculates the factorial of a number. | |
n! | |
""" | |
@spec fact(integer) :: integer | |
def fact(n) do | |
do_fact(n) | |
end | |
defp do_fact(n, acc \\ 1) | |
defp do_fact(0, acc), do: acc | |
defp do_fact(1, acc), do: acc | |
defp do_fact(n, acc) do | |
do_fact(n-1, n*acc) | |
end | |
@doc """ | |
Calculates n choose k | |
n! / ( k! * (n-k)! ) | |
""" | |
def n_choose_k(n, k) do | |
div(fact(n), fact(k) * fact(n-k)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment