Find the closest point pair and implement it in java

1. Introduction

The program prompts the user to enter the number of points. Read multiple points from the console and store them in a two-dimensional array called points. The program uses the variable shortestDistance to store the two closest points, and the subscripts of these two points in the points array are stored in p1 and p2. For each point with an index value of i, the program calculates the distance between points[i] and points[j] for all j>i. Whenever a distance shorter than the current shortest distance is found, the variables shortestDistance and p1 and p2 are updated.

2. Code

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

Three. Results display

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

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113730116