Nat*_*ley 2 c# sorting coordinates
我使用的是.NET 2.0,因此我无法访问漂亮的Linq; 但是,我编写了一些代码,用于顺时针/逆时针对点列表进行排序.
我的问题是,如果列表尚未排序,排序工作完全正常,但如果由于某种原因列表已经排序,则排序函数会失败.
如果有人可以帮我指出正确的方向,为什么这可能是原因,我就在徘徊.
这是我对这种类型的调用:
positions.Sort(new Comparison<Position>(MapUtils.SortCornersClockwise));
Run Code Online (Sandbox Code Playgroud)
这是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;
}
Run Code Online (Sandbox Code Playgroud)
我的参考位置是我确定点列表中每个点的相应角度的点.
现在说我有一个点列表:
15778066, 27738237
15778169, 27738296
15778185, 27738269
15778082, 27738210
Run Code Online (Sandbox Code Playgroud)
这些已按正确的顺序排序,但调用sort函数会产生:
15778082, 27738210
15778066, 27738237
15778185, 27738269
15778169, 27738296
Run Code Online (Sandbox Code Playgroud)
现在再拿一组样本点:
15778180, 27738255
15778081, 27738192
15778064, 27738219
15778163, 27738282
Run Code Online (Sandbox Code Playgroud)
此列表的顺序不正确,调用sort函数会产生:
15778064, 27738219
15778081, 27738192
15778180, 27738255
15778163, 27738282
Run Code Online (Sandbox Code Playgroud)
哪个是正确排序的.对于已经排序的每组坐标以及那些没有排序的坐标,这种模式会重复自我.有任何想法吗?
if (aTanA < aTanB) return -1;
else if (aTanB > aTanA) return 1;
Run Code Online (Sandbox Code Playgroud)
这两个条件是一样的!无论是交换变量或掉头的不等号,但不能同时使用.