forked from AlgorithmsMeetup/PreviousAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6a8d681
commit 546a4c7
Showing
2 changed files
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
var Quadtree = function(box) { | ||
this.box = box; | ||
this.point = null; | ||
this.SW = null; | ||
this.SE = null; | ||
this.NW = null; | ||
this.NE = null; | ||
}; | ||
|
||
Quadtree.prototype.insert = function(point) { | ||
if (!this.point) { | ||
this.point = point; | ||
} else { | ||
var quadrant = this.box.findQuadrantForPoint(point); | ||
if (!this[quadrant]) { | ||
this[quadrant] = new Quadtree(this.box.getQuadrant(quadrant)); | ||
} | ||
this[quadrant].insert(point); | ||
} | ||
}; | ||
|
||
Quadtree.prototype.findPointsWithin = function(searchBox) { | ||
var points = []; | ||
if (this.point && searchBox.contains(this.point)) { | ||
points.push(this.point); | ||
} | ||
|
||
if (this.SW && searchBox.overlaps(this.SW.box)) { | ||
points = points.concat(this.SW.findPointsWithin(searchBox)); | ||
} | ||
if (this.SE && searchBox.overlaps(this.SE.box)) { | ||
points = points.concat(this.SE.findPointsWithin(searchBox)); | ||
} | ||
if (this.NW && searchBox.overlaps(this.NW.box)) { | ||
points = points.concat(this.NW.findPointsWithin(searchBox)); | ||
} | ||
if (this.NE && searchBox.overlaps(this.NE.box)) { | ||
points = points.concat(this.NE.findPointsWithin(searchBox)); | ||
} | ||
|
||
return points; | ||
}; | ||
|
||
Quadtree.prototype.findNearestPointTo = function(target) { | ||
if (!this.point) { | ||
return null; | ||
} | ||
|
||
var xDist = 1; | ||
var yDist = 1; | ||
|
||
var searchBox = new Box(target.x - xDist, target.y - yDist, target.x + xDist, target.y + yDist); | ||
|
||
var points = this.findPointsWithin(searchBox); | ||
while (points.length === 0) { | ||
searchBox.expand(); | ||
points = this.findPointsWithin(searchBox); | ||
} | ||
|
||
var best = null; | ||
var bestDist = Infinity; | ||
for (var i = 0; i < points.length; i++) { | ||
var point = points[i]; | ||
var dist = point.distanceTo(target); | ||
if (dist < bestDist) { | ||
bestDist = dist; | ||
best = point; | ||
} | ||
} | ||
return best; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters