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.180 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/spiral-matrix/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/spiral-matrix/example.exs