How to fill an array with 1 and 0 in random locations with JavaScript

1 Answer

0 votes
function fillArrayWithRandom1and0(array) {
    const len = array.length;
    
    for (let i = 0; i < len; i++) {
        array[i] = Math.floor(Math.random() * 2); // Generates either 0 or 1
    }
}

const size = 10; 
let array = new Array(size);

fillArrayWithRandom1and0(array);

console.log(array.join(' '));

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

 



answered Jan 25 by avibootz
edited Jan 25 by avibootz
...