Code

Randomness generation

While working on a prototype of a web app, I needed to generate random boolean (true-or-false) values.

At first, I tried this:

1
var x = Math.random()>0.5;

Get this into a 2D array:

1
2
3
4
5
6
7
8
9
10
11
var array = [];
var 2DArray = [];

for(var i=0; i<10; i++) {
array.push(Math.random()>0.5);
}

for(var i=0; i<10; i++) {
2Darray.push(array);
array[i] = Math.random()>0.5;
}

The above ended up in 10 identical subarrays in the 2D array. Not what I wanted.

So I dug in Google and found this, which is

var x = !!Math.floor(Math.random() * 2)

VoilĂ !

#js