Menu
Coddy logo textTech

Common 2D Array Patterns

Part of the Logic & Flow section of Coddy's JavaScript journey. Lesson 13 of 65.

Certain patterns often appear when working with 2D arrays. Recognizing these patterns can help you solve problems more efficiently. Here are a few common patterns:

Diagonal Traversal

Accessing elements where the row index equals the column index (matrix[i][i]) gives you the main diagonal. For the anti-diagonal, the sum of the row and column indices equals the size of the array minus 1 (matrix[i][size - 1 - i]).

For example:

1  2  3
4  5  6
7  8  9

Traverse through main diagonal (matrix[i][i]): 1, 5, 9
Traverse through anti-diagonal (matrix[i][size - 1 - i]): 3, 5, 7

Border Traversal

To traverse the border elements, you keep one index constant (0 or size - 1) while iterating over the other.

To access the top border, you iterate over columns with the row index fixed at 0.

For example:

1  2  3  4
5  6  7  8
9 10 11 12

border elements: 1, 2, 3, 4, 8, 12, 11, 10, 9, 5 (all except 6 and 7)

challenge icon

Challenge

Easy

Create a function named printPatterns that takes a square 2D array of integers (matrix) as input and prints the following patterns:

  1. Main Diagonal: Print all elements where the row index equals the column index.
  2. Anti-Diagonal: Print all elements where the sum of the row and column indices equals the size of the matrix minus 1.
  3. Borders: Print the elements of the top, bottom, left, and right borders of the matrix.

The output should look like this:

Main Diagonal: 1 6 11 16 
Anti-Diagonal: 4 7 10 13 
Top Border: 1 2 3 4 
Bottom Border: 13 14 15 16 
Left Border: 1 5 9 13 
Right Border: 4 8 12 16

Try it yourself

function printPatterns(matrix) {
    let mainDiagonal = []
    // TODO: Implement
    console.log("Main Diagonal:", mainDiagonal.join(" "));
    
    let antiDiagonal = [];
    // TODO: Implement
    console.log("Anti-Diagonal:", antiDiagonal.join(" "));
    
    let topBorder = [];
    // TODO: Implement
    console.log("Top Border:", topBorder.join(" "));
    
    let bottomBorder = [];
    // TODO: Implement
    console.log("Bottom Border:", bottomBorder.join(" "));
    
    let leftBorder = [];
    // TODO: Implement
    console.log("Left Border:", leftBorder.join(" "));
    
    let rightBorder = [];
    // TODO: Implement
    console.log("Right Border:", rightBorder.join(" "));
}
// Do not write anything outside function
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online JavaScript compiler