How to rotate a matrix 90 degrees clockwise in JavaScript

2 Answers

0 votes
function rotate90Clockwise(matrix) {
    let N = matrix.length;

    // Step 1: Transpose the matrix
    for (let i = 0; i < N; i++) {
        for (let j = i; j < N; j++) {
            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
        }
    }

    // Step 2: Reverse each row
    for (let i = 0; i < N; i++) {
        matrix[i].reverse();
    }
}

function printMatrix(matrix) {
    matrix.forEach(row => console.log(row.join(" ")));
}

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log("Original Matrix:");
printMatrix(matrix);

rotate90Clockwise(matrix);

console.log("\nRotated Matrix:");
printMatrix(matrix);

  
  
/*
run:
      
Original Matrix:
1 2 3
4 5 6
7 8 9

Rotated Matrix:
7 4 1
8 5 2
9 6 3

*/
 

 



answered May 30 by avibootz
0 votes
function rotate90Clockwise(matrix) {
    let rows = matrix.length;
    let cols = matrix[0].length;
    
    let rotated = Array.from({ length: cols }, () => Array(rows).fill(0));

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            rotated[j][rows - 1 - i] = matrix[i][j]; // Mapping to rotated position
        }
    }
    return rotated;
}

function printMatrix(matrix) {
    matrix.forEach(row => console.log(row.join(" ")));
}

let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
];

console.log("Original Matrix:");
printMatrix(matrix);

let rotated = rotate90Clockwise(matrix);

console.log("\nRotated Matrix:");
printMatrix(rotated);

  
  
/*
run:
      
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12

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

*/
 

 



answered May 30 by avibootz
...