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

1 Answer

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

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

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

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

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


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

 



answered Jan 25, 2025 by avibootz

Related questions

1 answer 108 views
1 answer 96 views
1 answer 95 views
1 answer 96 views
1 answer 87 views
...