Last active
November 10, 2024 19:55
-
-
Save lbn/3d6963731261f76330af to your computer and use it in GitHub Desktop.
Pretty print a matrix in ES6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict" | |
function matprint(mat) { | |
let shape = [mat.length, mat[0].length]; | |
function col(mat, i) { | |
return mat.map(row => row[i]); | |
} | |
let colMaxes = []; | |
for (let i = 0; i < shape[1]; i++) { | |
colMaxes.push(Math.max.apply(null, col(mat, i).map(n => n.toString().length))); | |
} | |
mat.forEach(row => { | |
console.log.apply(null, row.map((val, j) => { | |
return new Array(colMaxes[j]-val.toString().length+1).join(" ") + val.toString() + " "; | |
})); | |
}); | |
} | |
// Try it! | |
let a = [[1,2,3],[4,5555555555555555555555,1],[0.000000000006, 7, 8]]; | |
matprint(a) | |
/* | |
1 2 3 | |
4 5.555555555555556e+21 1 | |
6e-12 7 8 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment