/**
* Function to mirror a matrix across its main diagonal
* @param {number[][]} matrix - The input 2D array (matrix)
* @returns {number[][]} - The mirror matrix
*/
function mirrorMatrix(matrix) {
// Validate input: Ensure it's a 2D array
if (!Array.isArray(matrix) || !matrix.every(row => Array.isArray(row))) {
throw new Error("Input must be a 2D array (matrix).");
}
const rows = matrix.length;
const cols = matrix[0].length;
// Create a new matrix with dimensions swapped
const mirror = Array.from({ length: cols }, () => Array(rows).fill(0));
// Fill the mirror matrix
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
mirror[j][i] = matrix[i][j];
}
}
return mirror;
}
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log("Original Matrix:");
console.table(matrix);
const mirroredMatrix = mirrorMatrix(matrix);
console.log("Mirrored Matrix:");
console.table(mirroredMatrix);
/*
run:
Original Matrix:
┌─────────┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │
├─────────┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 3 │
│ 1 │ 4 │ 5 │ 6 │
│ 2 │ 7 │ 8 │ 9 │
└─────────┴───┴───┴───┘
Mirrored Matrix:
┌─────────┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │
├─────────┼───┼───┼───┤
│ 0 │ 1 │ 4 │ 7 │
│ 1 │ 2 │ 5 │ 8 │
│ 2 │ 3 │ 6 │ 9 │
└─────────┴───┴───┴───┘
*/