How to transpose a matrix (swap rows and columns) in TypeScript

1 Answer

0 votes
type Matrix = number[][];

function print(matrix: Matrix): void {
    const rows: number = matrix.length;
    const cols: number = matrix[0].length;

    for (let i: number = 0; i < rows; i++) {
        let s = "";
        for (let j: number = 0; j < cols; j++) {
            s += matrix[i][j] + " ";
        }
        console.log(s);
    }
}

function transpose(matrix: Matrix): Matrix {
    return matrix[0].map((_, i) => matrix.map(row => row[i]));
}

let matrix: Matrix = [
    [1, 2, 3, 5],
    [4, 5, 6, 1],
    [7, 8, 9, 0]
];

matrix = transpose(matrix);

print(matrix);



/*
run:

1 4 7 
2 5 8 
3 6 9 
5 1 0 

*/

 



answered Jul 6, 2022 by avibootz
edited 1 day ago by avibootz
...