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

答案 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;
这是因为Math.round
细节。请改用Math.floor
:
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;