Skip to content

Instantly share code, notes, and snippets.

@MrSaints
Created July 1, 2015 19:49
Show Gist options
  • Save MrSaints/630fee597844d59af29b to your computer and use it in GitHub Desktop.
Save MrSaints/630fee597844d59af29b to your computer and use it in GitHub Desktop.
Pascal's triangle in Elixir (using recursion where possible).
# 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
@plu9in
Copy link

plu9in commented May 27, 2016

You could have written:
def pascal(n), do: pascal(n, [1, 1])
defp pascal(0, _), do: [1] # Not really coherent -- Should be 1 but it is easier for later use
defp pascal(1, acc), do: acc
defp pascal(n, acc) do
r = Enum.map(Enum.zip(acc ++ [0], [0 | acc]), fn {x, y} -> x+y end)
pascal(n-1, r)
end

Copy link

ghost commented Nov 16, 2016

Here is another way:

defmodule PascalTriangle do
  def draw(1), do: (IO.puts("1"); [1])
  def draw(current_level) do
    list = draw(current_level - 1)
    new_list = [1] ++ for(x <- 0..length(list)-1, do: Enum.at(list, x) + Enum.at(list, x+1, 0))
    Enum.join(new_list, " ") |> IO.puts
    new_list
  end
end

PascalTriangle.draw(5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment