javascript - 生成随机坐标(排除一些特定的)

标签 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),返回值需要一些时间。在那段时间(据我所知)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()

关于javascript - 生成随机坐标(排除一些特定的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872392/

相关文章:

javascript - 使用纯 Javascript 显示/隐藏组合框下拉列表

javascript - 将背景大小和背景位置的相对值转换为绝对 PX 值

多维表单提交后 PHP 递归创建数据库查询 : fk field sometimes "omitted", 但为什么以及如何修复?

javascript - String.charAt() 在循环中返回 undefined

c++ - 什么类型的随机数引擎用于指定的随机分布?

javascript - 在 React.js 中设置组件状态时遇到问题

javascript - 在 Javascript 中轻松添加值数组(例如,没有循环)

java - 随机化一个 BigInteger

java - 添加到 Collection 夹随机字符串并将其显示在 View 列表中

javascript - 以 count 作为值迭代对象