找出距离最近的点对,用java实现

一.介绍

程序提示用户输人点的个数。从控制台读取多个点,并将它们存储在一个名为points的二维数组中。程序使用变量shortestDistance来存储两个距离最近的点,而这两个点在points数组中的下标都存储在p1和p2中。对每一个索引值为i的点,程序会对所有的j>i计算points[i]和points[j]之间的距离。只要找到比当前最短距离更短的距离,就更新变量shortestDistance以及p1和p2。

二.代码

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));
    }
}

三.结果显示

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