请教Ruby实现HackerRank矩阵对角线差值问题的代码逻辑
Hey there! Let's break down that Ruby code for the Diagonal Difference problem step by step, focusing on the each_with_index loop that's got you stuck. First, let's recap the problem quickly: we need to calculate the absolute difference between the sum of elements on the main diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left) of an n×n matrix.
Example Code (the one you found)
Chances are the code looks something like this:
n = gets.to_i matrix = [] n.times { matrix << gets.split.map(&:to_i) } sum_main = 0 sum_secondary = 0 matrix.each_with_index do |row, i| sum_main += row[i] sum_secondary += row[n - 1 - i] end puts (sum_main - sum_secondary).abs
Let's Dive Into the each_with_index Loop
The each_with_index method is Ruby's way of iterating over an array while giving you both the current element and its position (index) in the array. Here's how it works for our matrix:
matrixis an array of arrays (each sub-array is a row of the matrix).- For every iteration:
rowis the current row we're looking at (e.g., the first iteration gives us the top row of the matrix).iis the index of that row (starts at 0, goes up to n-1).
What's happening inside the loop?
Main Diagonal Sum (
sum_main += row[i]):
The main diagonal consists of elements where the row index equals the column index. For example:- Row 0 (first row) → column 0
- Row 1 → column 1
- Row 2 → column 2
Sorow[i]grabs exactly the element on the main diagonal for the current row, and we add it tosum_main.
Secondary Diagonal Sum (
sum_secondary += row[n - 1 - i]):
The secondary diagonal is trickier—elements here have a column index equal ton-1 - row_index. Let's break that down:- For an n×n matrix, the last column has an index of
n-1(since Ruby uses 0-based indexing). - Row 0 → column
n-1 - 0 = n-1(last element of the first row) - Row 1 → column
n-1 -1 = n-2(second-to-last element of the second row) - Row n-1 → column
n-1 - (n-1) = 0(first element of the last row)
This formula perfectly targets every element on the secondary diagonal, which we add tosum_secondary.
- For an n×n matrix, the last column has an index of
Let's Test With a Concrete Example
Suppose we have a 3×3 matrix:
1 2 3 4 5 6 7 8 9
- Iteration 1 (i=0, row=[1,2,3]):
sum_main += 1→ sum_main = 1sum_secondary += 3→ sum_secondary =3 - Iteration 2 (i=1, row=[4,5,6]):
sum_main +=5→ sum_main=6sum_secondary +=5→ sum_secondary=8 - Iteration3 (i=2, row=[7,8,9]):
sum_main +=9→ sum_main=15sum_secondary +=7→ sum_secondary=15 - Final absolute difference:
|15-15| =0(which is correct!)
Why This Works So Well
Using each_with_index eliminates the need for manual counters (like a for loop with a separate variable). It keeps the code clean and readable, and directly ties the row position to the column positions we need for both diagonals.
内容的提问来源于stack exchange,提问作者Blank Reaver

