Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS generate random boolean

People also ask

How to generate random boolean in js?

Create an array containing 'true' and 'false' values. Calculate Math. random() and round its value. Use rounded value as the index to the array, to get boolean.

Does Math random include 0?

Math. random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.

How do you use math random in JavaScript?

In JavaScript, to get a random number between 0 and 1, use the Math. random() function. If you want a random number between 1 and 10, multiply the results of Math. random by 10, then round up or down.

How do you generate a random Boolean in C++?

Until now I used the following code to generate a random bool : bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);


You can compare Math.random() to 0.5 directly, as the range of Math.random() is [0, 1) (this means 'in the range 0 to 1 including 0, but not 1'). You can divide the range into [0, 0.5) and [0.5, 1).

var random_boolean = Math.random() < 0.5;

// Example
console.log(Math.random() < 0.1); //10% probability of getting true
console.log(Math.random() < 0.4); //40% probability of getting true
console.log(Math.random() < 0.5); //50% probability of getting true
console.log(Math.random() < 0.8); //80% probability of getting true
console.log(Math.random() < 0.9); //90% probability of getting true

If your project has lodash then you can:

_.sample([true, false])

Alternatively you can use your own sample function (source):

const sample = arr => arr[Math.floor(Math.random() * arr.length)];

For a more cryptographically secure value, you can use crypto.getRandomValues in modern browsers.

Sample:

var randomBool = (function() {
  var a = new Uint8Array(1);
  return function() {
    crypto.getRandomValues(a);
    return a[0] > 127;
  };
})();

var trues = 0;
var falses = 0;
for (var i = 0; i < 255; i++) {
  if (randomBool()) {
    trues++;
  }
  else {
    falses++;
  }
}
document.body.innerText = 'true: ' + trues + ', false: ' + falses;

Note that the crypto object is a DOM API, so it's not available in Node, but there is a similar API for Node.


!Math.round(Math.random());

­­­­­­­­­­­­­­


Impressed a lot by Kelvin's answer I would like to suggest a fairly similar but slightly enhanced solution.

var randomBoolean = Math.random() < 0.5;

This solution is a bit more obvious to read, because the number on the right-hand side of < tells you the probability of getting true rather than of getting false, which is more natural to comprehend. Also < is one symbol shorter than >=;


Potentialy faster solutions...

Bitwise operator approach i just thought of Math.random() + .5 >> 0 or ~~(Math.random() + .5). Here is a performance test to judge for yourself.

let randomBoolean = Math.random() + .5 >> 0;                 //chance of true
const randomBoolean = chance => Math.random() + chance >> 0; //chance of true

The bitwise operators is in this case essentially just the same as using Math.trunc() or Math.floor(), therefore this is also posible Math.trunc(Math.random() + .5).

let randomBoolean = Math.trunc(Math.random() + .5);
const randomBoolean = chance => Math.trunc(Math.random() + chance);

Other more common solutions

The more common way to get random boolean is probably a comparative approach like Math.random() >= .5 from Kelvin's answer or Math.random() < .5; from Arthur Khazbs's answer, they actualy output true & false, and not 1 & 0.

let randomBoolean = Math.random() >= .5;                 //chance of false
const randomBoolean = chance => Math.random() >= chance; //chance of false

let randomBoolean = Math.random()  < .5;                 //chance of true
const randomBoolean = chance => Math.random() < chance;  //chance of true

The only reason to use the Math.round(Math.random()) approach is simplicity and laziness.