我正在尝试制作一个非常简单的脚本来生成一个二维数组,其中每个第 n 个数组不包含它自己的索引作为元素,但包含随机数量的其他随机索引值作为其元素,并且不能为空。以下是我为尝试实现此目的而编写的一些代码:
totElList = []
numEls = 1000
for (i=0;i<numEls;i++) {
totElList[i] = []
for (j=0;j<numEls;j++) {
totElList[i][j] = j
}
}
for (i in totElList) {
totsplice = Math.round(Math.random()*(numEls-1))
totElList[i].splice(i,1)
for (j=0;j<totsplice;j++) {
rand = Math.round(Math.random()*totElList[i].length)
while (typeof(totElList[i][rand]) === undefined) {rand = Math.round(Math.random()*totElList[i].length)}
totElList[i].splice(rand,1)
}
}
问题是当我运行这个时,totElList 数组似乎比任何其他数字包含更多的 0,即使我假设元素会被随机删除。我做了一个测试来证实这一点。对于给定的 numEls,0 的数量始终是所有可能值中的最大值。我猜这与 Math.random() 和 Math.round() 的工作有关,但我不确定。有人可以给我一些见解吗?谢谢。
最佳答案
而不是 Math.round
,取Math.floor
这对于索引来说效果更好,因为它是从零开始的。
Example with one digit and a factor of 2 as index for an array with length of 2.
As you see, the second half index is moved to the next index of every number, which results into a wrong index and with the greatest random value, you get an index outside of the wanted length.
value round floor comment for round ----- ----- ----- ----------------- 0.0 0 0 0.1 0 0 0.2 0 0 0.3 0 0 0.4 0 0 0.5 1 0 wrong index 0.6 1 0 wrong index 0.7 1 0 wrong index 0.8 1 0 wrong index 0.9 1 0 wrong index 1.0 1 1 1.1 1 1 1.2 1 1 1.3 1 1 1.4 1 1 1.5 2 1 wrong index 1.6 2 1 wrong index 1.7 2 1 wrong index 1.8 2 1 wrong index 1.9 2 1 wrong index
关于javascript - Math.round(Math.random()) 组合似乎在我的 javascript 程序中生成了太多 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126536/