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 # 10Main 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, 9Transpose: 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
EasyThe square matrix is given (n × n). Print three lines, all derived from the patterns in the theory:
Anti-diagonal sum: <n>, the sum of cells wherer + c == matrix.length - 1Column sums: [...], the sum of each column. Hint: transpose first, then map each row to its sum, theninspectSymmetric: trueorfalse: 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: falseCheat sheet
Common 2D-array operations in Ruby:
Sum all cells — flatten then sum:
grid.flatten.sumMain 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 falseTry it yourself
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# TODO: anti-diagonal sum, column sums via transpose, symmetric check
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier32D Arrays
2D Array BasicsAccessing 2D ElementsIterating Over 2D ArraysCommon 2D PatternsRecap - Matrix Operations