Reputation: 129
Hi this is my problem I have an array of points P(x,y) and I need to sort these points from the furthest to the closest, respect to the barycenter of a Polygon, this what I have done (I know this is a bad solution ) how can I do a better and aboveall faster solution?
List<C2DPoint> OrderedGripperPoints = new List<C2DPoint> { };
while(myGripperPoints.Count!=0)
{
double dist=-1;
int index=-1;
for(int k=0;k<myGripperPoints.Count;k++)
{
if(myGripperPoints[k].Distance(WorkScrap.GetCentroid())>=dist)
{
index = k;
dist = myGripperPoints[k].Distance(WorkScrap.GetCentroid());
}
}
OrderedGripperPoints.Add(myGripperPoints[index]);
myGripperPoints.RemoveAt(index);
}
Thanks for your answers...
Upvotes: 0
Views: 2508
Reputation: 11478
Consider the following code:
Point Class (assumed class definition)
class Point
{
public int X { get; set;}
public int Y { get; set;}
}
Point EqualityComparer
class PointEqualityComparer : IEqualityComparer<Point>
{
public bool Equals(Point p1, Point p2) { return p1.X == p2.X && p1.Y == p2.Y; }
public int GetHashCode(Point p) { return p.X.GetHashCode() *31 + p.Y.GetHashCode()*23; }
}
Create a Dictionary with Point as Key and Distance as value (assuming integer):
Dictionary<Point,int> pointDictionary =
new Dictionary<Point, int>(new PointEqualityComparer());
Add Points as follows:
Point p = new Point {X = <value>, Y = <value>};
pointDictionary.Add(p,p.Distance(WorkScrap.GetCentroid()));
Order by Distance as follows:
pointDictionary.OrderByDescending(x => x.Value).ToList();
List<KeyValuePair<Point,int>>
, where elements are in Descending orderUpvotes: 1
Reputation: 2498
Use Linq to order points.
using System.Linq;
var sortedList = myGripperPoints.OrderBy(p => p.Distance(WorkScrap.GetCentroid())).ToList();
Upvotes: 4