gpt4 book ai didi

c# - 在 C# 数组中避免重复操作的最有效方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 08:49:00 27 4
gpt4 key购买 nike

我需要计算数组中每对点之间的距离,并且每对只想计算一次。我想出的方法是否足够有效或有更好的方法?这是一个示例,以及解释我要获取的内容的视觉效果:

diagram of code purpose

例如,首先获取片段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 更有效。

最佳答案

如果您有 n 个点,则所有点对的集合包含 n * (n-1)/2 个元素。那就是您正在执行的操作数。我要做的唯一改变是使用 Parallel.ForEach() 并行执行操作。

像这样(需要调试)

        int distArraySize = (pointsArray.Length * (pointsArray.Length - 1)) / 2;

var distanceArray = new double[distArraySize];

int numPoints = pointsArray.Length;

Parallel.ForEach<int>(Enumerable.Range(0, numPoints - 2),
currentPointIndex =>
{
Parallel.ForEach<int>(Enumerable.Range(currentPointIndex + 1, numPoints - 2),
otherPointIndex =>
{
double xDistance = pointsArray[otherPointIndex].X - pointsArray[currentPointIndex].X;
double yDistance = pointsArray[otherPointIndex].Y - pointsArray[currentPointIndex].Y;
double distance = Math.Sqrt(xDistance * xDistance + yDistance * yDistance);
int distanceArrayIndex = currentPointIndex * numPoints - (currentPointIndex * (currentPointIndex + 1) / 2) + otherPointIndex - 1;
distanceArray[distanceArrayIndex] = distance;
});
});

关于c# - 在 C# 数组中避免重复操作的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10583128/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com