function printMatrix(matrix) {
const rows = matrix.length; // number of rows
const cols = matrix[0].length; // number of columns
for (let i = 0; i < rows; i++) {
let row = '';
for (let j = 0; j < cols; j++) {
row += matrix[i][j].toString().padStart(4);
}
console.log(row);
}
}
function inverseMatrix(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
let counter = 0;
for (let i = 0, r = rows - 1; i < rows; i++, r--) {
for (let j = 0, c = cols - 1; j < cols; j++, c--) {
[matrix[i][j], matrix[r][c]] = [matrix[r][c], matrix[i][j]];
counter++;
if (counter > (rows * cols) / 2 - 1) return;
}
}
}
const matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
console.log('matrix:');
printMatrix(matrix);
inverseMatrix(matrix);
console.log('\ninverse matrix:');
printMatrix(matrix);
/*
run:
matrix:
1 2 3 4
5 6 7 8
9 10 11 12
inverse matrix:
12 11 10 9
8 7 6 5
4 3 2 1
*/