I've been asked recently to implement two classes that represent Point2D
points and Point3D
points. The distance and the other methods work fine, yet there's only one left that needs to be implemented and I can't figure out the algorithm. It's stated like this:
我最近被要求实现两个代表Point2D点和Point3D点的类。距离和其他方法工作正常,但只剩下一个需要实现,我无法弄清楚算法。这是这样说的:
"Given a set of points in space, determine that point from the set that is the closest to another point in space (that's not in the set)"
“给定空间中的一组点,确定距离最接近空间中另一个点的集合中的点(不在集合中)”
Below are the two classes. Can anybody help me with the last needed algorithm?
以下是两个班级。任何人都可以帮助我使用最后需要的算法吗?
public class Point2D {
protected double x;
protected double y;
public Point2D() { }
public Point2D(double x, double y)
{
this.x = x;
this.y = y;
}
public double getX() { return x; }
public void setX(double x) { this.x = x; }
public double getY() { return y; }
public void setY(double y) { this.y = y; }
public double Point2DDistance(Point2D punct)
{
double px = this.x - punct.x;
double py = this.y - punct.y;
return Math.sqrt((px * px) + (py * py));
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class Point3D extends Point2D {
private double z;
public Point3D() { }
public Point3D(double x, double y, double z)
{
super(x, y);
this.z = z;
}
public double getZ() { return z; }
public void setZ(double z) { this.z = z; }
public double Point3DDistance(Point3D punct)
{
double pz = this.z - punct.z;
return this.Point2DDistance(punct) + Math.sqrt(pz * pz);
}
public String toString() {
return "(" + this.x + ", " + this.y + ", " + this.z + ")";
}
}
1 个解决方案
#1
2
Iterate through the points.
通过积分迭代。
For each point,
对于每一点,
-
if this is the first point, set
min_distance
= the point's distance to the not-in-set point P, and copy this point toclosestP
, and如果这是第一个点,设置min_distance =点到非设置点P的距离,并将此点复制到nearestP,并且
-
otherwise, if this point's distance to P is less than
min_distance
, setmin_distance
to this point's distance, and copy this point toclosestP
.否则,如果此点到P的距离小于min_distance,则将min_distance设置为此点的距离,并将此点复制到nearestP。
Now closestP
holds the closest point, and min_distance
holds the distance it has from P.
现在,nearestP保持最近的点,min_distance保持它与P的距离。
Hurray!
#1
2
Iterate through the points.
通过积分迭代。
For each point,
对于每一点,
-
if this is the first point, set
min_distance
= the point's distance to the not-in-set point P, and copy this point toclosestP
, and如果这是第一个点,设置min_distance =点到非设置点P的距离,并将此点复制到nearestP,并且
-
otherwise, if this point's distance to P is less than
min_distance
, setmin_distance
to this point's distance, and copy this point toclosestP
.否则,如果此点到P的距离小于min_distance,则将min_distance设置为此点的距离,并将此点复制到nearestP。
Now closestP
holds the closest point, and min_distance
holds the distance it has from P.
现在,nearestP保持最近的点,min_distance保持它与P的距离。
Hurray!