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

时间:2015-11-23 13:33:39

标签: javascript arrays random

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

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 s),它需要一点返回一个值。在那段时间(据我所知),javascript无法做任何其他事情......所以一切都会暂停...

1 个答案:

答案 0 :(得分:1)

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

如果经常使用它,可以将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()