4

Basically I have a list of points, each with X,Y,Z (Z is always the same).

For example:

pointList.add(Point p = new Point(1, 2, 3));

however I am having trouble sorting them into a clockwise order.

I know the centre and I know the there are roughly 600 points in each list.

I have accomplished this before in Python, but I am having trouble in C#.

Python code:

pointlist.sort(key=lambda c:atan2(c[0], c[1]))
bolt19
  • 1,963
  • 4
  • 32
  • 41
  • Do you want your list to be sorted by default? If so, maybe it would be better to keep the points in one of the `Sorted` collections, using custom `IComparer` ([`SortedList`](http://msdn.microsoft.com/en-us/library/ms132319.aspx) or [`SortedDictionary`](http://msdn.microsoft.com/en-us/library/f7fta44c%28v=vs.110%29.aspx), [their performance differs](http://stackoverflow.com/a/935631/1180426)). – Patryk Ćwiek Mar 16 '14 at 10:01

2 Answers2

5

Not sure if this would accomplish what you need.

points = points.OrderBy(x => Math.Atan2(x.X, x.Y)).ToList();

Not very optimized or anything, just looked at your python code and thought this would accomplish the same.

Note: You may need using System.Linq unless you already have it.

Edit: Sturm pointed out that reversing the order might be necessary to get them 'clock-wise' One way of accomplishing this is using OrderByDescending instead of OrderBy.

t0yk4t
  • 854
  • 8
  • 10
  • If you need to iterate through the list 'after' you sort it. A better way of using this would be something like `foreach (var point in points.OrderBy(x => Math.Atan2(x.X, x.Y))) [do stuff with point]` since you're enumerating it 'while' you loop, instead of first enumerating it, then iterating. – t0yk4t Mar 16 '14 at 10:07
  • You might need to reverse the order if you want the clockwise order. – Sturm Mar 16 '14 at 10:09
  • @Sturm what do you mean 'might'? in some cases you will need to reverse and in others you want? how can you tell? – John Demetriou Oct 19 '15 at 10:53
  • @t0yk4t it doesnt work in this case https://stackoverflow.com/questions/60590066/finding-the-center-and-sorting-the-coordinates-in-clockwise-direction –  Mar 08 '20 at 17:59
4

For anyone struggling with how to sort around any point (XX, YY) not only (0,0) the code needs a slight modification.

points.OrderBy(x => Math.Atan2(x.X - XX, x.Y - YY)).ToList();
lukaszberwid
  • 1,097
  • 7
  • 19