Menu
Coddy logo textTech

Common 2D Patterns

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 13 of 56.

Some 2D-array operations show up so often they're worth recognizing by name.

Sum every cell: flatten the grid into a 1D array and call sum:

grid = [[1, 2], [3, 4]]
puts grid.flatten.sum  # 10

Main diagonal: the cells where row index equals column index (matrix[i][i]):

matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

(0...matrix.length).each do |i|
  puts matrix[i][i]
end
# 1, 5, 9

Transpose: Ruby has this built in. Rows become columns and vice-versa:

matrix.transpose
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Knowing these by name saves you from rewriting the same nested loops.

challenge icon

Challenge

Easy

The square matrix is given (n × n). Print three lines, all derived from the patterns in the theory:

  1. Anti-diagonal sum: <n>, the sum of cells where r + c == matrix.length - 1
  2. Column sums: [...], the sum of each column. Hint: transpose first, then map each row to its sum, then inspect
  3. Symmetric: true or false: is the matrix equal to its own transpose?

For the default matrix the output is:

Anti-diagonal sum: 15
Column sums: [12, 15, 18]
Symmetric: false

Cheat sheet

Common 2D-array operations in Ruby:

Sum all cells — flatten then sum:

grid.flatten.sum

Main diagonal — cells where row index equals column index (matrix[i][i]):

(0...matrix.length).each { |i| puts matrix[i][i] }
# i == 0: matrix[0][0], i == 1: matrix[1][1], ...

Anti-diagonal — cells where r + c == matrix.length - 1:

(0...matrix.length).each { |i| puts matrix[i][matrix.length - 1 - i] }

Transpose — rows become columns:

matrix.transpose
# [[1,4,7],[2,5,8],[3,6,9]]

Column sums — transpose first, then sum each row:

matrix.transpose.map(&:sum)  # [col0_sum, col1_sum, ...]

Check symmetry — compare matrix to its transpose:

matrix == matrix.transpose  # true or false

Try it yourself

matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

# TODO: anti-diagonal sum, column sums via transpose, symmetric check
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow