我有2个要点列表:
var listA = new List<Point>();
listA.Add(new Point(10, 1));
listA.Add(new Point(5, 5));
listA.Add(new Point(15, 35));
var listB = new List<Point>();
listB.Add(new Point(1, 1));
listB.Add(new Point(5, 4));
listB.Add(new Point(35, 15));
现在我想做类似的事情:
getClosesPoints(listA,listB, Out pointA, Out pointB);
我目前处于可以再次检查列表的位置1点
private int NearestPoint(Point srcPt, List<Point> lookIn)
{
if (lookIn.Count == 1)
return 0;
KeyValuePair<double, int> smallestDistance = new KeyValuePair<double, int>();
for (int i = 0; i < lookIn.Count; i++)
{
double distance = Math.Sqrt(Math.Pow(srcPt.X - lookIn[i].X, 2) + Math.Pow(srcPt.Y - lookIn[i].Y, 2));
if (i == 0)
smallestDistance = new KeyValuePair<double, int>(distance, i);
else if (distance < smallestDistance.Key)
smallestDistance = new KeyValuePair<double, int>(distance, i);
}
Console.WriteLine("smallest Distance:" + smallestDistance.Key);
return smallestDistance.Value;
}
但是我不确定如何扩展此代码以检查2个列表。
我假设您想在两个列表中找到最接近的两个点,其中一个点在一个列表中,另一个点在另一个列表中。
您可以通过使用内部和外部循环来解决此问题。外循环遍历第一个列表中的所有点。对于这些点中的每一个,您都可以使用内部循环将其与第二个列表中的所有点进行比较。
然后,您无需记住所有距离;您只需要记住到目前为止找到的两个最接近点之间的距离,以及到目前为止它们本身最接近的点。
您也可以创建一个简单的小类,仅返回最接近的两个点,而不是通过out
参数返回结果。为了方便起见,您可以Distance()
在此类中添加一个函数,因此您无需存储实际距离。(但是,如果您经常使用此值,那么您可能希望将距离缓存在本地字段中,而不是每次都进行计算。)
最后,FindClosestPoints()
方法的参数可以是,IEnumerable<Point>
而不是List<Point>
,它允许您将其与更多的收集类型一起使用。
将所有内容放在一起可以得到以下内容(可编译的控制台应用程序):
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Demo
{
// Class just used to return the result from FindClosestPoints()
public sealed class ClosestPoints
{
public ClosestPoints(Point p1, Point p2)
{
_p1 = p1;
_p2 = p2;
}
public Point P1 { get { return _p1; } }
public Point P2 { get { return _p2; } }
public double Distance()
{
double dx = P1.X - P2.X;
double dy = P1.Y - P2.Y;
return Math.Sqrt(dx*dx + dy*dy);
}
private readonly Point _p1;
private readonly Point _p2;
}
public static class Program
{
public static void Main()
{
var listA = new List<Point>();
listA.Add(new Point(10, 1));
listA.Add(new Point(5, 5));
listA.Add(new Point(15, 35));
var listB = new List<Point>();
listB.Add(new Point(1, 1));
listB.Add(new Point(5, 4));
listB.Add(new Point(35, 15));
var answer = FindClosestPoints(listA, listB);
Console.WriteLine("Closest points are {0} and {1}", answer.P1, answer.P2);
}
public static ClosestPoints FindClosestPoints(IEnumerable<Point> seq1, IEnumerable<Point> seq2)
{
double closest = double.MaxValue;
ClosestPoints result = null;
foreach (var p1 in seq1)
{
foreach (var p2 in seq2)
{
double dx = p1.X - p2.X;
double dy = p1.Y - p2.Y;
double distance = dx*dx + dy*dy;
if (distance >= closest)
continue;
result = new ClosestPoints(p1, p2);
closest = distance;
}
}
return result;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句