给定一个大小为 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/