基本上,我正在创建一个网格并在其上绘制点,并且没有两个点可以位于完全相同的位置 [(3,4) 与 (4,3) 不同]。 y 坐标必须在 2 和 7 之间(因此 2、3、4、5、6、7),x 坐标必须在 1 和 7 之间。我有一个 getRandom 函数(如下所示),它生成一个最小和最大范围之间的随机数。这是我到目前为止所拥有的。
var xposition = [];
var yposition = [];
var yShouldBeDifferentThan = []
function placeRandom() {
for (s=0; s<xposition.length ; s++ ) {
if (xposition[s] == x) { // loops through all numbers in xposition and sees if the generated x is similar to an existing x
yShouldBeDifferentThan.push(yposition[s]); //puts the corresponding y coordinate into an array.
for (r=0; r<yShouldBeDifferentThan.length; r++) {
while (y == yShouldBeDifferentThan[r]) {
y = getRandom(2,7);
}
}
}
}
xposition.push(x);
yposition.push(y);
}
问题在于,如果
xposition = [1, 5, 5, 7, 5, 5]
yposition = [1, 3, 7, 2, 3, 6]
yShouldBeDifferentThan = [3, 7, 3, 6]
首先,它会生成一个不同于 3 的随机数,比如 6。然后(我认为)它会看到:6 == 7
?事实并非如此。 6 == 3
?事实并非如此。 6 == 6?确实如此,因此生成一个不同于 6 的随机数。这就是问题所在,它可能会生成数字 3。我的 getRandom
函数如下:
function getRandom(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
我正在考虑制作 getRandom
函数,以便我也可以根据需要排除数字,但我不知道该怎么做。如果我可以让它排除数字,那么在 placeRandom
函数的最后一个 while 循环中,也许我可以这样做:
y = getRandom(2,7) // excluding all numbers which already exist in the ShouldBeDifferentThan array
另请注意,由于我使用的是 Internet Explorer 8,因此无法使用 indexOf
方法。
最佳答案
您的方法有两个问题:
您可以为已经满的行选择一个 x 坐标,这会将代码发送到永恒循环中。
选择一个 x 坐标,然后选择一个 y 坐标意味着位置将有不同的机会被选择,具体取决于之前在同一行中选择了多少个位置。
只需选择一个 x 和 y 坐标,然后检查之前是否选择了该特定坐标。如果是,请重新开始。
function placeRandom() {
do {
var x = getRandom(2,7), y = getRandom(2,7), found = false;
for (s = 0; s<xposition.length; s++) {
if (xposition[s] == x && yposition[s] == y) {
found = true;
break;
}
}
} while(found);
xposition.push(x);
yposition.push(y);
}
此外,当网格开始变满时(例如大约 80%),您可以创建一个包含所有剩余位置的数组,并从中随机选择一个。
关于Javascript - 生成范围内的随机数,不包括某些数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19451425/