给出大小为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)
答案 0 :(得分:0)
表情
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
答案 1 :(得分:0)
将2d数组转换为另一个2d数组,其中每个索引都包含{value,x,y}。现在按行/列对其进行排序。然后,每个元素搜索都将采用rlogc(按列排序)/ clogr(按行排序),仅输出该索引的(x,y)(不是实际坐标,而是给定坐标二维数组)