How to inverse N x M matrix in TypeScript

1 Answer

0 votes
// Function to print a matrix
function printMatrix(matrix: number[][]): void {
    const rows: number = matrix.length;           // number of rows
    const cols: number = matrix[0].length;        // number of columns

    for (let i = 0; i < rows; i++) {
        let row: string = '';
        for (let j = 0; j < cols; j++) {
            row += matrix[i][j].toString().padStart(4);
        }
        console.log(row);
    }
}

// Function to invert a matrix (reverse order of elements)
function inverseMatrix(matrix: number[][]): void {
    const rows: number = matrix.length;
    const cols: number = matrix[0].length;
    let counter: number = 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: number[][] = [
    [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

*/

 



answered May 17, 2024 by avibootz
edited 1 day ago by avibootz
...