最も近いポイントペアを見つけて、Javaで実装します

1.はじめに

プログラムは、ポイント数を入力するようにユーザーに促します。コンソールから複数のポイントを読み取り、それらをポイントと呼ばれる2次元配列に格納します。プログラムは変数shortestDistanceを使用して最も近い2つのポイントを格納し、これら2つのポイントの添え字をpoints配列に格納します。p1とp2に格納されます。プログラムは、インデックス値がiの各ポイントについて、すべてのj> iについてpoints [i]とpoints [j]の間の距離を計算します。現在の最短距離よりも短い距離が見つかると、変数shortestDistanceとp1およびp2が更新されます。

2.コード

package com.zhuo.base;

import java.util.Scanner;

public class FindNearestPoints {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of points: ");
        int numberOfPoints = input.nextInt();
        double[][] points = new double[numberOfPoints][2];//创建存储点数组
        System.out.print("Enter " + numberOfPoints + " points: ");
        for (int i = 0; i < points.length; i++) {
    
    
            points[i][0] = input.nextDouble();
            points[i][1] = input.nextDouble();
        }
        /*p1和p2是点数组中的索引*/
        int p1 = 0;
        int p2 = 1;
        double shotestDistance = distance(points[p1][0],points[p1][1],points[p2][0],points[p2][1]);//初始化最短距离
        /*计算每两点的距离*/
        for (int i = 0; i < points.length; i++) {
    
    
            for (int j = i + 1; j <points.length; j++) {
    
    
                double distance = distance(points[i][0], points[i][1], points[j][0], points[j][1]);
                if (shotestDistance > distance) {
    
    
                    p1 = i;
                    p2 = j;
                    shotestDistance = distance;
                }
            }
        }
        System.out.println("The closest tow points are: " + "(" + points[p1][0] + "," + points[p1][1] + ")"
                            + " and " + "(" + points[p2][0] + "," + points[p2][1] + ")");
    }
    /*计算两点(x1,y2)和(x2,y2)之间的距离的方法*/
    public static double distance(double x1, double y1, double x2, double y2) {
    
    
        return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
    }
}

3.結果の表示

Enter the number of points: 8
Enter 8 points: -1 3  -1 -1  1 1  2 0.5  2 -1  3 3  4 2  4 -0.5
The closest tow points are: (1.0,1.0) and (2.0,0.5)

Process finished with exit code 0

おすすめ

転載: blog.csdn.net/weixin_42768634/article/details/113730116