How to initialize a matrix with random characters in Node.js

1 Answer

0 votes
function printMatrix(matrix) {
    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            process.stdout.write(matrix[i][j] + ' ');
        }
        console.log();
    }
}

function initializeMatrixWithRandomCharacters(matrix) {
    const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            matrix[i][j] = characters.charAt(Math.floor(Math.random() * characters.length));
        }
    }
}

const ROWS = 3;
const COLS = 4;

const matrix = new Array(ROWS).fill(null).map(() => new Array(COLS));

initializeMatrixWithRandomCharacters(matrix);

printMatrix(matrix);

 
  
    
/*
run:
         
f 8 z o 
9 4 X z 
s 4 B G 

*/

 



answered May 18, 2024 by avibootz
...