生成随机坐标(不包括某些特定坐标)

Generate random coordinates (excluding some specific ones)

本文关键字:坐标 不包括 随机      更新时间:2023-09-26

我有一个多维数组,我将其用作一个非常简单的坐标系。为了生成随机坐标,我想出了一个非常简单的函数:

var coords = [
  [1,0,0,1,0,0,0,0,1,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1],
  [0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1],
  [1,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1],
  [1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,0,1,1],
  [1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1],
  [0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,1,0,1,1,0,1,1],
  [1,0,1,0,1,1,1,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1,1]
];
function getRandomInt( min, max ) {
  return Math.floor( Math.random() * (max - min + 1) ) + min;
}
function randomCoords() {
  var x, y;
  do {
    x = getRandomInt( 0, coords[ 0 ].length - 1 );
    y = getRandomInt( 0, coords.length - 1 );
  } 
  while ( coords[ y ][ x ] !== 1 );
  return [ x, y ];
}

正如您可能看到的,我只想得到数组中1的随机坐标。虽然这是有效的,但我想知道是否有更好/更有效的方法可以做到这一点?有时(尤其是在我的坐标系中有很多0的情况下)需要一点时间才能返回值。在那段时间里(据我所知)javascript不能做任何其他事情。。。所以一切都会暂停。。。

如果您只想获得一到两次随机坐标,那么您的解决方案是最好的。

如果你经常使用它,你可以把1的坐标放在一个数组中。因此,您只需要在数组上使用random()一次coordPairs1[Math.floor(Math.random() * coordPairs1.length)]

var coords = [
  [1,0,0,1,0,0,0,0,1,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1],
  [0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1],
  [1,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1],
  [1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,0,1,1],
  [1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1],
  [0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,1,0,1,1,0,1,1],
  [1,0,1,0,1,1,1,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1,1]
];
// make coord-pairs:
var coordPairs1 = []
for(var x=0; x<coords[0].length; ++x) {
    for(var y=0; y<coords.length; ++y) {
        if(coords[y][x] == 1)
            coordPairs1.push([x,y])
    }
}
function randomCoords() {
    return coordPairs1[Math.floor(Math.random() * coordPairs1.length)]
}
// Example:
document.body.innerHTML = randomCoords()