我有一点如fixedPoint = (142, 12)
。我想随机创建n(x,y)点。然后我想计算从C {中fixedPoint
到其他(x,y)
点的最近距离。
是否有教程解释如何完成此操作?或者任何示例代码?
答案 0 :(得分:3)
这只是通过各个点循环并使用毕达哥拉斯定理来找到距离,并跟踪最佳匹配。
基本上(伪代码 - 自从我在C#工作以来已经有一段时间了):
struct Point
{
public int x;
public int y;
};
var fixed = new Point(142,42);
const int numberOfPoints = 20; // arbitrary number
List<Point> points = new List<Point>(numberOfPoints);
var random = new Random();
for(int i = 0; i < numberOfPoints; ++i)
{
int x = random.Next(-200,200);
int y = random.Next(-200,200);
points.Add(new Point(x,y));
}
Point closestPoint = null;
float closestDistanceSquared = float.Max;
/// find closest point to fixed
foreach(var point in points)
{
var distanceSquared = Math.Pow(point.x - fixed.x,2) + Math.Pow(point.y - fixed.y,2);
if (distanceSquared < closestDistanceSquared)
{
closestDistanceSquared = distanceSquared;
closestPoint = point;
}
}
/// closestPoint is now a reference to the closest to fixedPoint
/// distance between the two is Math.Sqrt(distanceSquared)
我使用平方距离而不是在循环中取平方根,因为它的效率稍高,足以进行距离比较。
值得注意的是,您可以在生成点时执行此操作,而不是单独循环。