c# - Elegant LINQ solution for finding Max/Min/Avg/etc. euclidean disdance between points -
assume have list of points , want find max/min/avg/etc. euclidean disdance between them. there elegant linq solution?
static void main(string[] args) { list<point> points = new list<point>() { new point(1, 1), new point(2, 2), new point(40, 50), new point(100, 25) }; int mineucdistance = ?? } /// <summary> /// return distance between 2 points /// </summary> public static double euclidean(point p1, point p2) { return math.sqrt(math.pow(p1.x - p2.x, 2) + math.pow(p1.y - p2.y, 2)); }
one way generate cartesian product of points, producing possible pairs of points, , compute euclidean distances between them. have list of distance numbers, rest trivial:
var pointwithindex = points.select((x, i) => new { point = x, index = i}); var pointpairs = p1 in pointwithindex p2 in pointwithindex p1.index > p2.index select { p1 = p1.point, p2 = p2.point }; var distances = pointpairs.select(x => euclidean(x.p1, x.p2)).tolist(); double mineucdistance = distances.min();
of course assumes not have lot of points, cause o(n^2).
Comments
Post a Comment