-1

我最近被要求实现两个代表Point2D点和Point3D点的类。距离和其他方法工作正常,但只剩下一个需要实现,我无法弄清楚算法。它是这样声明的:

“给定空间中的一组点,从集合中确定最接近空间中另一个点的点(不在集合中)”

下面是两个类。有人可以帮我解决最后需要的算法吗?

    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 + ")";
    }
}
4

1 回答 1

2

遍历这些点。

对于每个点,

  • 如果这是第一个点,则设置min_distance= 该点到未设置点P的距离,并将该点复制到closestP, 和

  • 否则,如果该点到P的距离小于min_distance,则设置min_distance为该点的距离,并将该点复制到closestP

现在closestP保存最近的点,并min_distance保存它与P的距离。

欢呼!

于 2012-11-12T13:39:07.313 回答