gpt4 book ai didi

C#顺时针排序X,Y坐标列表

转载 作者:行者123 更新时间:2023-11-30 19:07:08 25 4
gpt4 key购买 nike

我使用的是 .NET 2.0,所以我无法访问漂亮的 Linq;但是,我已经编写了一些代码来顺时针/逆时针对点列表进行排序。

我的问题是,如果列表尚未排序,则排序工作得很好,但如果由于某种原因列表已经排序,则排序功能会严重失败。

我正在徘徊,是否有人可以帮助我指出正确的方向,说明为什么这可能是原因。

这是我对排序的调用:

positions.Sort(new Comparison<Position>(MapUtils.SortCornersClockwise));

这里是 SortCornersClockwise 函数:

public static int SortCornersClockwise( Position A, Position B)
{
// Variables to Store the atans
double aTanA, aTanB;

// Reference Point
Pixels reference = Program.main.reference;

// Fetch the atans
aTanA = Math.Atan2(A.Pixel.Y - reference.Y, A.Pixel.X - reference.X);
aTanB = Math.Atan2(B.Pixel.Y - reference.Y, B.Pixel.X - reference.X);

// Determine next point in Clockwise rotation
if (aTanA < aTanB) return -1;
else if (aTanB > aTanA) return 1;
return 0;
}

我的引用点是我确定点列表中每个点的相应角度的点。

现在假设我有一个点列表:

15778066, 27738237
15778169, 27738296
15778185, 27738269
15778082, 27738210

这些已经按正确顺序排序,但调用排序函数会产生:

15778082, 27738210
15778066, 27738237
15778185, 27738269
15778169, 27738296

现在取另一组样本点:

15778180, 27738255
15778081, 27738192
15778064, 27738219
15778163, 27738282

此列表的顺序不正确,调用排序函数会产生:

15778064, 27738219
15778081, 27738192
15778180, 27738255
15778163, 27738282

排序正确。对于已排序的和未排序的每组坐标,此模式会自行重复。有什么想法吗?

最佳答案

if (aTanA < aTanB) return -1;
else if (aTanB > aTanA) return 1;

这两个条件是一样的! 要么交换变量要么改变不等号,但不能同时改变。

关于C#顺时针排序X,Y坐标列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996942/

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