How to initialize a matrix with random characters in TypeScript

1 Answer

0 votes
function printMatrix(matrix: string[][]) {
    for (let i: number = 0; i < matrix.length; i++) {
        for (let j: number = 0; j < matrix[i].length; j++) {
            process.stdout.write(matrix[i][j] + ' ');
        }
        console.log();
    }
}
 
function initializeMatrixWithRandomCharacters(matrix: string[][]) {
    const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
    for (let i: number = 0; i < matrix.length; i++) {
        for (let j: number = 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: string[][] = new Array(ROWS).fill(null).map(() => new Array(COLS));
 
initializeMatrixWithRandomCharacters(matrix);
 
printMatrix(matrix);
 
  
   
     
/*
run:
          
8 O t l 
Z b M y 
m Z C b 
 
*/

 



answered May 18, 2024 by avibootz
...