找到JAVA中最接近的两个点

时间:2016-04-06 15:44:29

标签: java eclipse multidimensional-array

     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。

2 个答案:

答案 0 :(得分:0)

您总是分配值&#34; 1&#34;到pointNum1,所以这个值将始终显示:

pointNum1 = 1;

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

pointNum2 = r + 1;

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

答案 1 :(得分:0)

您总是将其中一个值设置为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);
    }
}