在Actionscript 3中查找最接近的3个目标
时间:2020-03-06 14:59:24 来源:igfitidea点击:
我有一个由点组成的字符数组,我想采用任何字符,并能够遍历该数组并找到最接近的前3个(使用Point.distance)邻居。谁能给我一个关于如何做到这一点的想法?
解决方案
这是我昨晚发布的代码的新版本和改进版本。它由两个类PointPointer和TestCase组成。这次,我也能够对其进行测试!
我们从TestCase.as开始
package {
import flash.geom.Point;
import flash.display.Sprite;
public class TestCase extends Sprite {
public function TestCase() {
// some data to test with
var pointList:Array = new Array();
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(1, 2));
pointList.push(new Point(9, 9));
// the point we want to test against
var referencePoint:Point = new Point(10, 10);
var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);
trace("referencePoint is at", referencePoint.x, referencePoint.y);
for each(var result:Object in resultPoints) {
trace("Point is at:", result.point.x, ", ", result.point.y, " that's ", result.distance, " units away");
}
}
}
}
这将是PointTester.as
package {
import flash.geom.Point;
public class PointTester {
public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{
// this array will hold the results
var resultList:Array = new Array();
// loop over each point in the test data
for each (var testPoint:Point in pointList) {
// we store the distance between the two in a temporary variable
var tempDistance:Number = getDistance(testPoint, referencePoint);
// if the list is shorter than the maximum length we don't need to do any distance checking
// if it's longer we compare the distance to the last point in the list, if it's closer we add it
if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) {
// we store the testing point and it's distance to the reference point in an object
var tmpObject:Object = { distance : tempDistance, point : testPoint };
// and push that onto the array
resultList.push(tmpObject);
// then we sort the array, this way we don't need to compare the distance to any other point than
// the last one in the list
resultList.sortOn("distance", Array.NUMERIC );
// and we make sure the list is kept at at the proper number of entries
while (resultList.length > maxCount) resultList.pop();
}
}
return resultList;
}
public static function getDistance(point1:Point, point2:Point):Number {
var x:Number = point1.x - point2.x;
var y:Number = point1.y - point2.y;
return Math.sqrt(x * x + y * y);
}
}
}
值得一提的是,如果点数足够大以至于重要的性能,那么可以通过保留两个点列表(一个由X排序,另一个由Y排序)来更快地实现目标。通过遍历每个点,最接近O(logn)时间的3个点,而不是O(n)时间。
如果我们使用grapefrukt的解决方案,则可以将getDistance方法更改为return x * x + y * y;而不是return Math.sqrt(x * x + y * y);。

