Sha256: 584c3e86ea2b466c15d38094e39c21c42e5c86a394fecfe3d276e4ec4e256f8e

Contents?: true

Size: 692 Bytes

Versions: 69

Compression:

Stored size: 692 Bytes

Contents

defmodule Spiral do
  @doc """
  Given the dimension, return a square matrix of numbers in clockwise spiral order.
  """
  @spec matrix(dimension :: integer) :: list(list(integer))
  def matrix(0), do: []

  def matrix(dimension) do
    unwind(dimension, dimension, 1)
  end

  defp unwind(row, col, start) do
    case col do
      0 ->
        [[]]

      _ ->
        [
          Enum.to_list(start..(start + col - 1))
          | unwind(col, row - 1, start + col) |> rotate_right
        ]
    end
  end

  defp rotate_right(matrix) do
    matrix |> transpose |> Enum.map(&Enum.reverse/1)
  end

  defp transpose(matrix) do
    matrix |> List.zip() |> Enum.map(&Tuple.to_list/1)
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.138 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.137 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.136 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.135 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.134 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.133 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.132 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.131 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.130 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.129 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.128 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.127 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.126 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.125 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.124 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.123 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.122 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.121 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.120 tracks/elixir/exercises/spiral-matrix/example.exs