Skip to content

Instantly share code, notes, and snippets.

@mkreyman
Last active February 15, 2018 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkreyman/1891aaa70e41a3519a7487e7742a5eda to your computer and use it in GitHub Desktop.
Save mkreyman/1891aaa70e41a3519a7487e7742a5eda to your computer and use it in GitHub Desktop.
Spiral traversal of a multidimensional list of characters
# Given a multidimensional list of characters, print out a spiral traversal of the lists.
#
# iex(1)> matrix = [~w(A B C D), ~w(E F G H), ~w(I J K L), ~w(M N O P)]
# [
# ["A", "B", "C", "D"],
# ["E", "F", "G", "H"],
# ["I", "J", "K", "L"],
# ["M", "N", "O", "P"]
# ]
# iex(2)> Spiral.traverse(matrix, [])
# "A B C D H L P O N M I E F G K J"
defmodule Spiral do
def traverse([], list), do: list |> Enum.join(" ")
def traverse([row|[]], list) do
list = list ++ row
traverse([], list)
end
def traverse(matrix, list) do
[row | matrix] = matrix
list = list ++ row
matrix
|> transpose()
|> traverse(list)
end
defp transpose(matrix) do
matrix
|> List.zip()
|> Enum.map(&Tuple.to_list/1)
|> Enum.reverse()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment