求JavaScript通用for循环实现矩阵行、列及双对角线数值转换
Hey there! Let's work through those matrix transformations together. You already have the row transformation down, so I'll help you implement the column, backslash (), and slash (/) diagonal conversions using clear, readable for loops—making sure everything works for any size matrix, not just your 4x4 example.
First, let's define a constant for the "X" value to keep our code clean and avoid hardcoding:
const PLAYER = "X";
1. Row Transformation (Optimized)
I tweaked your existing row transformation code to avoid modifying the original input matrix (mutating inputs can lead to unexpected bugs later):
const transformRows = (matrix) => { return matrix.map(row => { let count = 0; return row.map(cell => { if (cell === PLAYER) { count++; return count; } else { count = 0; return 0; } }); }); };
2. Column Transformation
For columns, we'll iterate over each column first, then traverse down the rows in that column. We'll maintain a running count that resets when we hit a null:
const transformColumns = (matrix) => { const rows = matrix.length; if (rows === 0) return []; const cols = matrix[0].length; // Initialize a result matrix filled with zeros (matches input size) const result = Array.from({ length: rows }, () => Array(cols).fill(0)); for (let col = 0; col < cols; col++) { let count = 0; // Traverse down the current column for (let row = 0; row < rows; row++) { if (matrix[row][col] === PLAYER) { count++; result[row][col] = count; } else { count = 0; result[row][col] = 0; } } } return result; };
3. Backslash () Diagonal Transformation
Backslash diagonals share the same row - column value (e.g., (0,0), (1,1), (2,2) all have row-col = 0). We'll iterate over all possible row-col differences, then process each cell in that diagonal:
const transformBackslashDiagonals = (matrix) => { const rows = matrix.length; if (rows === 0) return []; const cols = matrix[0].length; const result = Array.from({ length: rows }, () => Array(cols).fill(0)); // The range of possible (row - col) values goes from -(cols-1) to rows-1 for (let diff = -(cols - 1); diff <= rows - 1; diff++) { let count = 0; // Check each row to see if it belongs to this diagonal for (let row = 0; row < rows; row++) { const col = row - diff; // Only process valid column indices if (col >= 0 && col < cols) { if (matrix[row][col] === PLAYER) { count++; result[row][col] = count; } else { count = 0; result[row][col] = 0; } } } } return result; };
4. Slash (/) Diagonal Transformation
Slash diagonals share the same row + column value (e.g., (0,3), (1,2), (2,1) all have row+col = 3). We'll iterate over all possible row+col sums, then process each cell in that diagonal:
const transformSlashDiagonals = (matrix) => { const rows = matrix.length; if (rows === 0) return []; const cols = matrix[0].length; const result = Array.from({ length: rows }, () => Array(cols).fill(0)); // The maximum possible (row + col) value is (rows-1)+(cols-1) const maxSum = (rows - 1) + (cols - 1); for (let sum = 0; sum <= maxSum; sum++) { let count = 0; // Calculate valid row range for this sum (avoids out-of-bounds columns) const startRow = Math.max(0, sum - cols + 1); const endRow = Math.min(rows - 1, sum); // Traverse the diagonal from top-right to bottom-left for (let row = startRow; row <= endRow; row++) { const col = sum - row; if (matrix[row][col] === PLAYER) { count++; result[row][col] = count; } else { count = 0; result[row][col] = 0; } } } return result; };
Test It Out!
You can run this code with your input matrix to verify the results match your examples:
const inputMatrix = [ ["X", "X", null, null], [null, "X", "X", "X"], [null, null, "X", "X"], ["X", "X", null, null] ]; console.log("Row Transformation:", transformRows(inputMatrix)); console.log("Column Transformation:", transformColumns(inputMatrix)); console.log("Backslash Diagonal Transformation:", transformBackslashDiagonals(inputMatrix)); console.log("Slash Diagonal Transformation:", transformSlashDiagonals(inputMatrix));
All these functions are generic (work for any m×n matrix), readable, and avoid mutating the original input—just like you asked!
内容的提问来源于stack exchange,提问作者MansouriAla

