제목에서 알 수 있듯이 재귀 함수에서 평면 배열 출력을 만드는 가장 효율적인 방법을 찾고 있습니다.
다음 예제는 올바른 결과를 생성하지만 각 재귀 수준에 대해 임시로 연결된 포인트 배열을 만들어야하므로 다소 느립니다.
class QuadTree {
// ...
// some other methods
// ...
get points() {
if (this.divided) {
// concatenate and return points of all subtrees
return this.subtrees[0].points.concat(
this.subtrees[1].points,
this.subtrees[2].points,
this.subtrees[3].points
);
}
// return _points array of this quadtree
return this._points;
}
}
속도를 높일 수있는 방법이 있습니까?
이러한 종류의 문제는 중첩 / 트리 형 데이터 구조로 작업 할 때 매우 일반적이라고 생각하지만 만족스러운 솔루션을 찾지 못했습니다.
내가 생각할 수있는 유일한 것은 접근 자 속성을 함수로 바꾸고 (또는 함수를 함께 추가) 대상 배열을 전달하여 직접 채울 수 있도록하는 것입니다. 다음과 같은 것 :
class QuadTree {
// ...
// some other methods
// ...
getDividedPoints(target = []) {
this.subtrees[0].getDividedPoints(target);
this.subtrees[1].getDivdedPoints(target);
this.subtrees[2].getDivdedPoints(target);
this.subtrees[3].getDivdedPoints(target);
return target;
}
get points() {
if (this.divided) {
return this.getDividedPoints([]);
}
// return _points array of this quadtree
return this._points;
}
}
또는 subtrees
일반 배열 인 getDividedPoints
경우 다음과 같을 수 있습니다.
getDividedPoints(target = []) {
this.subtrees.forEach(subtree => subtree.getDividedPoints(target));
return target;
}
그렇지 않으면 this.subtrees[0].points
(삽입하는 대신) 복사를 원한다고 가정하므로 concat
'꽤 괜찮을 것입니다.
하위 트리가 분할되거나 분할되지 않는 if
경우 함수 에이 필요합니다 . 그리고 저는 뒤늦게 수업 이름을 알아 챘습니다. :-) 그래서 아마도 네 번의 호출을 할 것입니다.
getPoints(target) {
if (this.divided) {
target = target || [];
this.subtrees[0].getPoints(target);
this.subtrees[1].getPoints(target);
this.subtrees[2].getPoints(target);
this.subtrees[3].getPoints(target);
return target;
}
if (target) {
target.push.apply(target, this._points);
return target;
}
return this._points; // <== If you're really okay with giving this
// to the caller (you were in your original code)
}
get points() {
return this.getDividedPoints([]);
}
... 또는 그 기본 아이디어에 대한 몇 가지 다른 회전 중 하나.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다