我需要计算数组中每对点之间的距离,并且只想执行一次。我想知道我想出来的方法是否足够高效,或者是否有更好的方法?这里有一个示例,以及一个图形来解释我想要获得什么:
例如,首先获取A-B、A-C、A-D这些线段;然后是B-C、B-D;最后是C-D。换句话说,我们想在新数组中保留A-B,但不要B-A,因为那会是重复的。var pointsArray = new Point[4];
pointsArray[0] = new Point(0, 0);
pointsArray[1] = new Point(10, 0);
pointsArray[2] = new Point(10, 10);
pointsArray[3] = new Point(0, 10);
// using (n * (n-1)) / 2 to determine array size
int distArraySize = (pointsArray.Length*(pointsArray.Length - 1))/2;
var distanceArray = new double[distArraySize];
int distanceArrayIndex = 0;
// Loop through points and get distances, never using same point pair twice
for (int currentPointIndex = 0; currentPointIndex < pointsArray.Length - 1; currentPointIndex++)
{
for (int otherPointIndex = currentPointIndex + 1;
otherPointIndex < pointsArray.Length;
otherPointIndex++)
{
double xDistance = pointsArray[otherPointIndex].X - pointsArray[currentPointIndex].X;
double yDistance = pointsArray[otherPointIndex].Y - pointsArray[currentPointIndex].Y;
double distance = Math.Sqrt(Math.Pow(xDistance, 2) + Math.Pow(yDistance, 2));
// Add distance to distanceArray
distanceArray[distanceArrayIndex] = distance;
distanceArrayIndex++;
}
}
由于这将与成千上万的点一起使用,我认为一个精确尺寸的数组比使用任何类型的IEnumerable更有效。