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.29 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.28 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.27 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.26 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.25 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.24 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.23 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.22 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.21 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.20 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.19 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.18 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.17 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.16 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.15 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.14 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.13 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.12 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.11 tracks/elixir/exercises/pascals-triangle/example.exs
trackler-2.2.1.10 tracks/elixir/exercises/pascals-triangle/example.exs