javascript - 在网格中查找随机放置的元素 (x,y)

标签 javascript algorithm

给定一个大小为 1000 的网格,找出随机放置的元素的 x 和 y 坐标。

我已尝试将网格分割为四个部分,但我还必须使解决方案的时间复杂度高效。

const GRID_SIZE = 1000

class RandomElement {
  constructor() {
    const element = {
      x: Math.floor(Math.random() * GRID_SIZE),
      y: Math.floor(Math.random() * GRID_SIZE)
    }
    this._element = element
  }

  findInArea(x1, y1, x2, y2) {
    console.log(`Scanning area (${x1}, ${y1}, ${x2}, ${y2})`)
    return (
      this._element.x >= x1 &&
      this._element.y >= y1 &&
      this._element.x < x2 &&
      this._element.y < y2
    )
  }

  findInCell(x, y) {
    console.log(`Scanning cell (${x}, ${y}`)
    return this._element.x === x && this._element.y === y
  }
}

const RandomElement = new RandomElement()

const iselementHere1 = RandomElement.findInArea(0, GRID_SIZE, 0, GRID_SIZE)
console.log('Is element Here?', iselementHere1)

const iselementHere2 = RandomElement.findInArea(0, GRID_SIZE / 2, GRID_SIZE / 2, GRID_SIZE)
console.log('Is element Here?', iselementHere2)

const iselementHere3 = RandomElement.findInArea(GRID_SIZE / 2, 0, GRID_SIZE, GRID_SIZE / 2)
console.log('Is element Here?', iselementHere3)

const iselementHere4 = RandomElement.findInArea(GRID_SIZE / 2, GRID_SIZE / 2, GRID_SIZE, GRID_SIZE)
console.log('Is element Here?', iselementHere4)

最佳答案

表达式

xx = Math.floor(this._element.x / (GRID_SIZE / 2))
yy = Math.floor(this._element.y / (GRID_SIZE / 2))

为您提供 2x2 网格中的单元格坐标。

你可以将两者组合在一个参数中

cellYX = xx + 2 * yy

获取结果 0..3 作为单元格编号

0  |  1
-------
2  |  3   

关于javascript - 在网格中查找随机放置的元素 (x,y),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57099806/

相关文章:

javascript - 根据用户选择过滤 JSON 嵌套数组

javascript - 如何将嵌套 map 假设为原型(prototype)?

c# - 您如何在 .NET 的算法代码中断言?

c++ - C++ 中的多维复数值数组

javascript - $scope.$on ('$routeChangeSuccess' ...) 和调用作用域函数中的方法有什么区别?

javascript - 读取 JSON 消息的值

javascript - Async.waterfall 的 native 回调函数

algorithm - 在数据库中表示阶梯的最佳方式

algorithm - 之前和之后的集合发生了什么变化

python - 找到最大化正确多数决定数量的预测子集