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

1 Answer

0 votes
function fillArrayWithRandom1and0(array: number[]) {
    const len: number = array.length;

    for (let i: number = 0; i < len; i++) {
        array[i] = Math.floor(Math.random() * 2); // Generates either 0 or 1
    }
}

const size: number = 10;
let array: number[] = new Array(size);

fillArrayWithRandom1and0(array);

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

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

 



answered Jan 25, 2025 by avibootz

Related questions

...