小组列表

时间:2014-09-15 03:20:21

标签: c# list grouping points

我有一个点列表,我需要通过更接近的点进行分组。

这些点是我在这里用红色圈出的白点:

illustration

点是X和Y坐标,这里是按X排序的样本。

+        [0]    {X = 435 Y = 347}    System.Drawing.Point
+        [1]    {X = 435 Y = 348}    System.Drawing.Point
+        [2]    {X = 434 Y = 347}    System.Drawing.Point
+        [3]    {X = 434 Y = 348}    System.Drawing.Point
+        [4]    {X = 434 Y = 349}    System.Drawing.Point
+        [5]    {X = 433 Y = 201}    System.Drawing.Point
+        [6]    {X = 433 Y = 202}    System.Drawing.Point
+        [7]    {X = 433 Y = 348}    System.Drawing.Point
+        [8]    {X = 432 Y = 149}    System.Drawing.Point
+        [9]    {X = 432 Y = 200}    System.Drawing.Point
+        [10]    {X = 432 Y = 201}    System.Drawing.Point
+        [11]    {X = 432 Y = 202}    System.Drawing.Point
+        [12]    {X = 432 Y = 203}    System.Drawing.Point
+        [13]    {X = 431 Y = 148}    System.Drawing.Point
+        [14]    {X = 431 Y = 149}    System.Drawing.Point
+        [15]    {X = 431 Y = 200}    System.Drawing.Point
+        [16]    {X = 431 Y = 201}    System.Drawing.Point
+        [17]    {X = 431 Y = 202}    System.Drawing.Point
+        [18]    {X = 431 Y = 203}    System.Drawing.Point
+        [19]    {X = 430 Y = 148}    System.Drawing.Point
+        [20]    {X = 430 Y = 149}    System.Drawing.Point
+        [21]    {X = 349 Y = 69}    System.Drawing.Point
+        [22]    {X = 349 Y = 70}    System.Drawing.Point

我需要将所有更近的点分组,然后计算质心(实际上我的问题是将所有更近的点放在一起)。

我知道有一个公式来计算2点之间的欧几里德距离,并且找到(使用范围)最接近给定点的点,但不确定如何使用LINQ或其他方法在C#中。

3 个答案:

答案 0 :(得分:2)

[编辑]关于最近点问题,你可以迭代每个点并检查更接近距离R的点(dist(点a,点b)< R)。这样,您就可以定义您认为接近给定点的内容。

关于Center of Mass上的问题,您可以做的是,对于每个坐标,将每个值相加并除以点数。例如:

foreach (var point in Points)
{
    xCenterOfMass +=  point.X;
    yCenterOfMass +=  point.Y;
}

xCenterOfMass /= Points.Count();
yCenterOfMass /= Points.Count();

答案 1 :(得分:0)

如果我理解你正在尝试做什么,(有点困难,因为你的措辞可能更好)你想要按每个点到某个未知位置的距离订购一个列表。

您的问题并不清楚,因此我假设您希望将它们按距离原点分组。在这种情况下,LINQ看起来像这样:

var output = points.OrderBy(p1 => Math.Pow(p1.X, 2) + Math.Pow(p1.Y, 2));

其中points是您的List<Point>

如果您正在寻找通过到任意点的距离来订购它们,那么它看起来会像这样:

var output = points.OrderBy(p1 => Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y -p2.Y, 2)));

其中p2是您想要找到距离的点,pointsList<Point>的位置。

来源:

http://msdn.microsoft.com/en-us/library/system.drawing.point(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/bb549422.aspx

http://en.wikipedia.org/wiki/Distance#Geometry

答案 2 :(得分:0)

组点的已知解决方案是k均值聚类算法。

http://en.wikipedia.org/wiki/K-means_clustering

这也将为您提供每个群体的质量中心。