【发布时间】:2023-03-27 22:20:02
【问题描述】:
如何在一系列点中找到中心以创建四叉树节点并有效地做到这一点?
class point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
//range = [] of points, (they get sorted into quarters in the tree node)
一个范围代表一个点数组,代表一个棋盘。
以下是相关代码:
class quadtreeNode {
constructor(range, parent, depth) {
const centerPoint = findCenter(range);
this.center = centerPoint;
this.parent = parent;
if (range.length <= 1) {
this.leaf = true;
this.value = this.center;
} else {
this.TL = new quadtreeNode(
range.filter(x => x.x < this.center.x && x.y < this.center.y),
this,
depth + 1
);
this.TR = new quadtreeNode(
range.filter(x => x.x > this.center.x && x.y < this.center.y),
this,
depth + 1
);
this.BL = new quadtreeNode(
range.filter(x => x.x < this.center.x && x.y > this.center.y),
this,
depth+1
);
this.BR = new quadtreeNode(
range.filter(x => x.x > this.center.x && x.y > this.center.y),
this,
depth + 1
);
}
}
}
还有:
findCenter(array){
let centerPoint = null;
if (array.length <= 1) {
centerPoint = array[0];
} else {
let minX = array.sort((x, y) => x.x < y.x)[0];
let minY = array.sort((x, y) => x.y < y.y)[0];
let maxX = array.sort((x, y) => x.x > y.x)[0];
let maxY = array.sort((x, y) => x.y > y.y)[0];
const targetX = maxX-minX;
const targetY = maxY-minY;
const target = array.find(x => x.x == targetX && x.y == targetY);
if (!target) {
return array[(Math.floor(array.length / 2))];
} else {
centerPoint = target;
}
}
return centerPoint;
}
我对如何找到中心有点困惑,我是否需要每次都找到确切的中心,或者是否有四叉树的估计,或者范围是否应该是一个特定长度可被...整除4?
【问题讨论】:
标签: javascript tree quadtree