# JS生成随机布尔值

2020/11/16 03:22 · javascript ·  · 0评论

const rand = Boolean(Math.round(Math.random()));

a）以上是最佳做法吗？

b）我在想什么吗？

c）我在想什么吗？

d）有我不知道的更好/更快/更优雅的方式吗？

（如果B和C是互斥的，也有些兴趣。）

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"

_.sample([true, false])

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

### 样品：

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;

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

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

var randomBoolean = Math.random() < 0.5;

# 潜在的更快解决方案...

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

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

## 其他更常见的解决方案

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

return Math.round((Math.random() * 1) + 0) === 0;

const crypto = require('crypto');
const randomBool = (function () {
let a = new Uint8Array(1);
return function () {
crypto.randomFillSync(a);
return a[0] > 127;
};
})();

let trues = 0;
let falses = 0;
for (let i = 0; i < 100; i++) {
if (randomBool()) {
trues++;
}
else {
falses++;
}
}

console.log('true: ' + trues + ', false: ' + falses);