Created
July 1, 2015 19:49
-
-
Save MrSaints/630fee597844d59af29b to your computer and use it in GitHub Desktop.
Pascal's triangle in Elixir (using recursion where possible).
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
# Author: MrSaints | |
# License: MIT | |
defmodule Factorial do | |
def recursive(n, acc) when n === 1 or n === 0 do | |
acc | |
end | |
def recursive(n, acc) do | |
temp = n - 1 | |
recursive(temp, acc * temp) | |
end | |
def recursive(n) do | |
acc = n | |
recursive(n, acc) | |
end | |
def enum(n) do | |
Enum.reduce n..1, fn(x, acc) -> | |
x * acc | |
end | |
end | |
end | |
defmodule PascalsTriangle do | |
def element(row, column) when column === 0 or row === column do | |
1 | |
end | |
def element(row, column) when column === 1 do | |
row + 1 | |
end | |
def element(row, column) do | |
result = Factorial.recursive(row) / | |
(Factorial.recursive(column) * Factorial.recursive(row - column)) | |
trunc result | |
end | |
def row(n, current, acc) when current > n do | |
acc | |
end | |
def row(n, current, acc) do | |
newTuple = Tuple.insert_at(acc, current, element(n, current)) | |
row n, current + 1, newTuple | |
end | |
def row(n) do | |
row n, 1, {element(n, 0)} | |
end | |
def rows(n, current, acc) when n === current do | |
acc | |
end | |
def rows(n, current, acc) do | |
rows n, current + 1, acc ++ [row(current)] | |
end | |
def rows(n) do | |
rows n, 1, [row(0)] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is another way: