Recap - Matrix Operations
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 14 of 56.
Pull together creation, access, iteration, and the common patterns in one challenge.
Challenge
MediumRead n from input, the size of a square matrix. Build an n × n matrix where each cell at row r, column c equals r + c.
Then print, on separate lines:
- The matrix using
inspecton the outer array - The sum of all cells
- The maximum value on the main diagonal
- The transpose using
inspect
For input 3, the output is:
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
18
4
[[0, 1, 2], [1, 2, 3], [2, 3, 4]](For this construction, the matrix happens to equal its own transpose.)
Try it yourself
n = gets.to_i
# TODO: build the n×n matrix and print the four required lines
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