用于查找 Max/Min/Avg/etc 的优雅 LINQ 解决方案。点之间的欧氏距离
Elegant LINQ solution for finding Max/Min/Avg/etc. euclidean disdance between points
假设我有点列表并且我想找到 Max/Min/Avg/etc。它们之间的欧氏距离。有没有优雅的LINQ方案?
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 the 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));
}
一种方法是生成所有点的笛卡尔积,有效地生成所有可能的点对,然后计算它们之间的欧氏距离。然后你将只有一个距离数字列表,所以其余的都是微不足道的:
var pointWithIndex = points.Select((x, i) => new { Point = x, Index = i});
var pointPairs =
from p1 in pointWithIndex
from p2 in pointWithIndex
where 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();
当然这是假设你没有很多点,因为这是 O(n^2)。
假设我有点列表并且我想找到 Max/Min/Avg/etc。它们之间的欧氏距离。有没有优雅的LINQ方案?
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 the 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));
}
一种方法是生成所有点的笛卡尔积,有效地生成所有可能的点对,然后计算它们之间的欧氏距离。然后你将只有一个距离数字列表,所以其余的都是微不足道的:
var pointWithIndex = points.Select((x, i) => new { Point = x, Index = i});
var pointPairs =
from p1 in pointWithIndex
from p2 in pointWithIndex
where 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();
当然这是假设你没有很多点,因为这是 O(n^2)。