Skip to content

Instantly share code, notes, and snippets.

@aifrak
Created August 20, 2022 11:46
Show Gist options
  • Select an option

  • Save aifrak/c6e6bdb3ca5487769c9d39cc465f820e to your computer and use it in GitHub Desktop.

Select an option

Save aifrak/c6e6bdb3ca5487769c9d39cc465f820e to your computer and use it in GitHub Desktop.
Matrix manipulation in Elixir

Matrix manipulation in Elixir

Initialize matrix

matrix = [
  [1, 2, 3, 4, 5],
  [16, 17, 18, 19, 6],
  [15, 24, 25, 20, 7],
  [14, 23, 22, 21, 8],
  [13, 12, 11, 10, 9]
]
[
  [1, 2, 3, 4, 5], 
  [16, 17, 18, 19, 6], 
  [15, 24, 25, 20, 7], 
  [14, 23, 22, 21, 8], 
  [13, 12, 11, 10, 9]

Transpose

transposed_matrix = Enum.zip_with(matrix, & &1)
[
  [1, 16, 15, 14, 13],
  [2, 17, 24, 23, 12],
  [3, 18, 25, 22, 11],
  [4, 19, 20, 21, 10],
  [5, 6, 7, 8, 9]
]

Source: https://stackoverflow.com/a/70232481

Rotate right (clockwise)

Enum.map(transposed_matrix, &Enum.reverse/1)
[
  [13, 14, 15, 16, 1],
  [12, 23, 24, 17, 2],
  [11, 22, 25, 18, 3],
  [10, 21, 20, 19, 4],
  [9, 8, 7, 6, 5]
]

Source: https://exercism.org/tracks/elixir/exercises/spiral-matrix/solutions/rslopes

Rotate left (anticlockwise)

Enum.reverse(transposed_matrix)
[
  [5, 6, 7, 8, 9],
  [4, 19, 20, 21, 10],
  [3, 18, 25, 22, 11],
  [2, 17, 24, 23, 12],
  [1, 16, 15, 14, 13]
]

Inspired from: https://stackoverflow.com/a/52765940

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment