Computer >> Computer tutorials >  >> Programming >> Javascript

Square matrix rotation in JavaScript


We are required to write a JavaScript function that takes in an array of arrays of n * n order (square matrix). The function should rotate the array by 90 degrees (clockwise). The condition is that we have to do this in place (without allocating any extra array).

For example −

If the input array is −

const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

Then the rotated array should look like −

const output = [
   [7, 4, 1],
   [8, 5, 2],
   [9, 6, 3],
];

Example

Following is the code −

const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
const rotateArray = (arr = []) => {
   for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
      for (let columnIndex = rowIndex + 1; columnIndex < arr.length;
      columnIndex += 1) {
         [
            arr[columnIndex][rowIndex],
            arr[rowIndex][columnIndex],
         ] = [
            arr[rowIndex][columnIndex],
            arr[columnIndex][rowIndex],
         ];
      }
   }
   for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
      for (let columnIndex = 0; columnIndex < arr.length / 2;
      columnIndex += 1) {
         [
            arr[rowIndex][arr.length - columnIndex - 1],
            arr[rowIndex][columnIndex],
         ] = [
            arr[rowIndex][columnIndex],
            arr[rowIndex][arr.length - columnIndex - 1],
         ];
      }
   }
};
rotateArray(arr);
console.log(arr);

Output

Following is the output on console −

[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]