Skip to content

Instantly share code, notes, and snippets.

@IrhaAli
Created December 7, 2022 15:46
Show Gist options
  • Save IrhaAli/72712e270600c9b7a7103b856de306bf to your computer and use it in GitHub Desktop.
Save IrhaAli/72712e270600c9b7a7103b856de306bf to your computer and use it in GitHub Desktop.
Get transpose of a matrix. Worked with @Megwilken
const transpose = function (matrix) {
let rows = matrix.length;
let col = matrix[0].length;
let transpose = [...Array(col)].map(row => Array(rows));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < col; j++) {
transpose[j][i] = matrix[i][j];
}
}
return transpose;
};
// Do not edit this function.
const printMatrix = (matrix) => {
for (const row of matrix) {
for (const el of row) {
process.stdout.write(el + " ");
}
process.stdout.write("\n");
}
};
printMatrix(
transpose([
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
])
);
console.log("----");
printMatrix(
transpose([
[1, 2],
[3, 4],
[5, 6],
])
);
console.log("----");
printMatrix(transpose([[1, 2, 3, 4, 5, 6, 7]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment