随机数发生器很少包括上限和下限

时间:2018-03-04 17:56:45

标签: javascript

我有一些数组中的字母,只有8个,从A开始到H结束。使用典型的随机数生成器,我发现很少生成A和H.如何才能使这两个界限更具包容性?



{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}




3 个答案:

答案 0 :(得分:2)

 var i = Math.round(Math.random() * (allowedLetters.length - 1));

因为第一个和最后一个元素的范围为0.5,所有其他元素都获得1。可能会这样做:

var i = Math.floor(Math.random() * allowedLetters.length);

所有元素都得到相同的分布。

答案 1 :(得分:1)

round是错误的,因为随机值的一半时隙只到较低的索引,而一半的时隙到达上面的索引。



var values = ["A", "B", "C", "D", "E", "F", "G", "H"],
    index,
    count = {},
    i = 1e6;

while (i--) {
    index = Math.round(Math.random() * (values.length - 1));
    count[values[index]] = (count[values[index]] || 0) + 1;
}

console.log(count);




您可以使用Math.floor将数组的全长作为因子。



var values = ["A", "B", "C", "D", "E", "F", "G", "H"],
    index,
    count = {},
    i = 1e6;

while (i--) {
    index = Math.floor(Math.random() * values.length);
    count[values[index]] = (count[values[index]] || 0) + 1;
}

console.log(count);




答案 2 :(得分:0)



var allowedLetters = ["A","B","C","D","E","F","G","H"];
var calledTimes = [0,0,0,0,0,0,0,0];
var i = 0;

while (i++ < 100000) calledTimes[Math.round(Math.random() * (allowedLetters.length - 1))]++;

console.log(calledTimes);
&#13;
&#13;
&#13;

这是因为Math.round细节。请改用Math.floor

&#13;
&#13;
var allowedLetters = ["A","B","C","D","E","F","G","H"];
var calledTimes = [0,0,0,0,0,0,0,0];
var i = 0;

while (i++ < 100000) calledTimes[Math.floor(Math.random() * allowedLetters.length)]++;

console.log(calledTimes);
&#13;
&#13;
&#13;