0

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...

3
  • Is it possible to precompute distance at creation time of C2DPoint? Commented Oct 27, 2016 at 6:58
  • @NiyokoYuliawan yeas it is Commented Oct 27, 2016 at 7:16
  • You can use Array.Sort too Commented Oct 27, 2016 at 7:19

2 Answers 2

4

Use Linq to order points.

using System.Linq;

var sortedList = myGripperPoints.OrderBy(p => p.Distance(WorkScrap.GetCentroid())).ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer
It should be OrderByDescending, based on the question posted
1

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();
  1. Ordering is done by Distance in Descending order as expected
  2. Result would be List<KeyValuePair<Point,int>>, where elements are in Descending order

2 Comments

This solution provides you much more fine grain control over the process of Ordering as many more properties can be part of the Dictionary <key,value> and can be used in the Ordered collection
@AntonínLejsek thanks for pointing out, is this one better. Guarantee of having unique hash still may not be there, but will reduce the clash

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.