Javascript - 生成范围内的随机数,不包括某些数字

2024-01-11

基本上我正在创建一个网格并在其上绘制点,并且没有两个点可以位于完全相同的位置[(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函数,这样我也可以根据需要排除数字,但我不知道该怎么做。如果我可以让它排除数字,那么在最后一个 while 循环中placeRandom函数,也许我可以做类似的事情:

y = getRandom(2,7) // excluding all numbers which already exist in the ShouldBeDifferentThan array

另请注意,我无法使用indexOf方法,因为我使用的是 Internet Explorer 8。


您的方法有两个问题:

  • 您可以为已经满的行选择一个 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%),您可以创建一个包含所有剩余位置的数组,并从中随机选择一个。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript - 生成范围内的随机数,不包括某些数字 的相关文章

随机推荐