Sha256: 9f5539dc344acfa154d916a321440c654e919233956431cddf0a60bb741a8151

Contents?: true

Size: 620 Bytes

Versions: 327

Compression:

Stored size: 620 Bytes

Contents

defmodule PascalsTriangle do
  @doc """
  Calculates the rows of a pascal triangle
  with the given height
  """
  @spec rows(integer) :: [[integer]]
  def rows(num) do
    do_rows(num - 1, [[1]])
  end

  defp do_rows(0, rows), do: Enum.reverse rows
  defp do_rows(n, rows = [h | _]) do
    do_rows(n - 1, [next_row(h) | rows])
  end

  defp next_row(list) do
    list
    |> each_cons
    |> Enum.map(fn [a, b] -> a + b end)
    |> add_ends
  end

  defp each_cons(list) do
    list
    |> Enum.flat_map(&[&1, &1])
    |> Enum.slice(1..-2)
    |> Enum.chunk(2)
  end

  defp add_ends(list), do: [1] ++ list ++ [1]
end

Version data entries

327 entries across 327 versions & 1 rubygems

Version Path
trackler-2.2.1.109 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.108 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.107 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.106 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.105 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.104 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.103 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.102 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.101 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.100 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.99 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.98 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.97 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.96 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.95 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.94 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.93 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.92 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.91 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.90 tracks/elixir/exercises/pascals-triangle/example.exs