3x3 matrix or NxN matrix input [[3,6,9],[2,5,8],[1,4,7]] output [[1,2,3],[4,5,6],[7,8,9]]


3x3 matrix or NxN

// Check if the input is a valid 3x3 matrix
if (matrix.length !== 3 || !matrix.every(row => row.length === 3)) {
throw new Error("Invalid input: Matrix must be 3x3");
}

Following is sample javascript code.


function transformMatrix(matrix) {
  // Check if the input is a square matrix
  const n = matrix.length;
  if (!matrix.every(row => row.length === n)) {
    throw new Error("Invalid input: Matrix must be square");
  }

   // Determine the size of the matrix

  // Create the output matrix
  const outputMatrix = [];


   let currentSubArr=[];
   let j=0;
   
   for (let i = 0; i < n; i++) {
     
      currentSubArr.push(matrix[i][j])
    //console.log(currentSubArr)
      if(i+1 === n && j !== n) {
        i = -1;
        j ++;
        outputMatrix.push(currentSubArr);
        currentSubArr=[]
      }
    
   }


  // Reverse each row of the output matrix
  outputMatrix.reverse();

  return outputMatrix;
}

console.log(transformMatrix([[1,2,3],[4,5,6],[7,8,9]]))

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

console.log(transformMatrix([[2,3],[4,5,6],[9,8,9]]))

output :: throw new Error("Invalid input: Matrix must be square");