java实现平面4点最小距离

已知平面上若干个点的坐标。

需要求出在所有的组合中,4个点间平均距离的最小值(四舍五入,保留2位小数)。

比如有4个点:a,b,c,d, 则平均距离是指:ab, ac, ad, bc, bd, cd 这6个距离的平均值。

每个点的坐标表示为:横坐标,纵坐标

坐标的取值范围是:1~1000

例如,如果程序输入:
10,10
20,20
80,50
10,20
20,10

则程序应该输出:
11.38

package com.liu.ex5;

import java.util.ArrayList;
import java.util.Scanner;

public class Main1 {
    public static ArrayList<point> list = new ArrayList<point>();
    public static double minDistance = Double.MAX_VALUE;
    
    static class point {
        public double x;
        public double y;
        point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
    
    public double getDistance(point a, point b) {
        double result = Math.sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
        return result;
    }
    
    public void getResult() {
        double[][] distance = new double[list.size()][list.size()];  //获取所有点之间的距离
        for(int i = 0;i < list.size();i++) {
            point a = list.get(i);
            for(int j = i + 1;j < list.size();j++) {
                point b = list.get(j);
                distance[i][j] = getDistance(a, b);
                distance[j][i] = distance[i][j];
            }
        }
        
        for(int a = 0;a < list.size();a++) {
            for(int b = a + 1;b < list.size();b++) {
                double temp1 = distance[a][b];
                if(temp1 > minDistance)
                    continue;
                for(int c = b + 1;c < list.size();c++) {
                    double temp2 = distance[a][b] + distance[a][c] + distance[b][c];
                    if(temp2 > minDistance)
                        continue;
                    for(int d = c + 1;d < list.size();d++) {
                        double temp = distance[a][b] + distance[a][c] + distance[a][d]+
                        distance[b][c] + distance[b][d] + distance[c][d];
                        if(temp < minDistance)
                            minDistance = temp;
                    }
                }
            }
        }
        minDistance = minDistance / 6;
        System.out.printf("%.2f", minDistance);
    }
    
    public static void main(String[] args) {
        Main1 test = new Main1();
        Scanner in = new Scanner(System.in);
        while(true) {
            String a = in.nextLine();
            if(a.equals(null) || a.equals(""))
                break;
            String[] temp = a.split(",");
            double x = Double.valueOf(temp[0]);
            double y = Double.valueOf(temp[1]);
            list.add(new point(x,y));
        }
        test.getResult();
    }
}
posted @ 2019-07-25 19:23  南墙1  阅读(35)  评论(0编辑  收藏  举报