Fast algorithm to find the x closest points to a given point on a plane

后端 未结 4 592
猫巷女王i
猫巷女王i 2020-12-05 11:59

I would like to find a fast algorithm in order to find the x closest points to a given point on a plane.

We are actually dealing with not too many points (between 1

4条回答
  •  醉话见心
    2020-12-05 12:48

    For a given point (not all of them) and as the number of points is not extreme, you could calculate the distance from each point:

    var points = new List();
    Point source = ...
    ....
    var closestPoints = points.Where(point => point != source).
                               OrderBy(point => NotReallyDistanceButShouldDo(source, point)).
                               Take(20);
    
    private double NotReallyDistanceButShouldDo(Point source, Point target)
    {
       return Math.Pow(target.X - source.X, 2) + Math.Pow(target.Y - source.Y, 2);
    }
    

    (I've used x = 20)

    The calculation are based on doubles so the fpu should be able to do a decent job here. Note that you might get better performance if Point is a class rather than a struct.

提交回复
热议问题