繁体   English   中英

在JAVA中找到最近的两点

[英]Find the closest two points in JAVA

     public static void main(String[] args) {
    final String TITLE = "Lab 11 by ";
    double [][] points = {{1,2,3},{0,0,2},{1,3,5},{0,1,1}};
    double minDistance = distanceBetween(points[0],points[1]);
    int pointNum1 = 0; int pointNum2 = 1;
    for(int p = 0; p < points.length-1; p++){
        for(int r = p +1; r< points.length;r++){
        if(distanceBetween(points[p],points[r])<minDistance){
        minDistance =distanceBetween(points[p],points[r]);
        pointNum1 = 1;
        pointNum2 = r;
        } 
}
}
    String output = " Find closest two points!" + "\n" + "Points to consider:  \n";
    output += showPoints(points);
    output += "\n" + "Minimum distance is " + minDistance + "." + "\n";
    output += " The closest two points are " + pointNum1 + " and " + pointNum2 + ".";


    JOptionPane.showMessageDialog(null,output,TITLE,JOptionPane.INFORMATION_MESSAGE);
    } // end main

我认为我的问题是在这里我的两个最接近的点应该是 2 和 4,但我的打印出 1 和 3。

您将始终为 pointNum1 分配值“1”,因此该值将始终显示:

pointNum1 = 1;

在 pointNum2 中,您正在分配数组索引。 数组从 0 开始,而不是从 1 开始,因此您必须分配:

pointNum2 = r + 1;

即使你的程序得到了正确的结果,也会输出 1 和(正确的点 - 1)。

您总是将您的值之一设置为 1 并忽略数组的基于零的索引性质。 这是您测试的更正版本。 我做了一些小的性能更正,并包含了我用于计算点之间距离的代码。

public class Test {
    public static void main(String[] args) {
        final String TITLE = "Lab 11 by ";
        double [][] points = { { 1, 2, 3 }, { 0, 0, 2 }, { 1, 3, 5 }, { 0, 1, 1 } };
        double minDistance = 1000000000;
        int pointNum1 = -1;
        int pointNum2 = -1;
        for (int p = 0; p < points.length - 1; p++) {
            for (int r = p +1; r < points.length; r++) {
                double distance = distanceBetween(points[p], points[r]);
                if (distance < minDistance) {
                    minDistance = distance;
                    pointNum1 = p;
                    pointNum2 = r;
                } 
            }
        }

        // These lines simply move from the zero based indices to more meaningful numbers.
        pointNum1++;
        pointNum2++;

        System.out.println("The shortest distance is between point " +
            pointNum1 + " and point " + pointNum2 + ".");
    }

    private static double distanceBetween(double[] p1, double[] p2) {
        double total = 0;
        for (int i = 0; i < p1.length; i++) {
            total += Math.pow(p1[i] - p2[i], 2);
        }

        return Math.sqrt(total);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM