Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to fill a matrix with 1 and 0 in random locations with TypeScript

1 Answer

0 votes
const ROWS = 5;
const COLS = 4;

function fillMatrixWithRandom0And1(matrix: number[][], rows: number, cols: number) {
    for (let i: number = 0; i < rows; i++) {
        for (let j: number = 0; j < cols; j++) {
            matrix[i][j] = Math.floor(Math.random() * 2); // Generates either 0 or 1
        }
    }
}

function printMatrix(matrix: number[][], rows: number, cols: number) {
    for (let i: number = 0; i < rows; i++) {
        let row = '';
        for (let j: number = 0; j < cols; j++) {
            row += matrix[i][j] + ' ';
        }
        console.log(row);
    }
}

const matrix: number[][] = Array.from({ length: ROWS }, () => Array(COLS).fill(0));

fillMatrixWithRandom0And1(matrix, ROWS, COLS);
  
printMatrix(matrix, ROWS, COLS);


  
/*
run:
  
"1 0 1 0 " 
"0 0 0 0 " 
"0 1 0 0 " 
"0 0 1 0 " 
"1 0 0 1 "
  
*/

 



answered Jan 25, 2025 by avibootz

Related questions

1 answer 83 views
1 answer 79 views
1 answer 66 views
1 answer 71 views
1 answer 64 views
...