日期:2014-05-20  浏览次数:20658 次

最小距离
已知平面上若干个点的坐标。
需要求出在所有的组合中,4个点间平均距离的最小值(四舍五入,保留2位小数)。
比如有4个点:a,b,c,d,则平均距离是指:ab, ac, ad, bc, bd, cd 这6个距离的平均值。
每个点的坐标表示为:横坐标,纵坐标
坐标的取值范围是:1~1000
所有点的坐标记录在in.txt中,请读入该文件,然后计算。
注意:我们测试您的程序的时候,in.txt 可能会很大,比如包含上万条记录。
举例:
如果,in.txt 内的值为:

10,10
20,20
80,50
10,20
20,10

则程序应该输出:
11.38

------解决方案--------------------
如果点过多的话可能会有问题

package com.common.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;


public class Test {
public static void main(String[] args) throws Exception {
List<Point> pointList = new ArrayList<Point>();
FileReader fr = new FileReader("d:\\data.txt");
BufferedReader reader = new BufferedReader(fr);
String str = null;
while(true){
str = reader.readLine();
if(str == null) {
break;
}
pointList.add(new Point(str.split(",")));
}
int length = pointList.size();
int count = 0;//int count = length * (length - 1) / 2; 这样就不用再循环里加了
double totalDistance = 0;
for(int i = 0; i < length; i++) {
Point p1 = pointList.get(i);
for(int j = i + 1; j < length; j++) {
Point p2 = pointList.get(j);
count++;
totalDistance +=  Math.sqrt(Math.pow(p2.getX() - p1.getX(), 2) + Math.pow(p2.getY() - p1.getY(), 2));
}
}
double avgDistance = totalDistance / count;
System.out.printf("平均距离为:%.2f", avgDistance);
}
}  

class Point {
private int x;

private int y;

public Point() {

}

public Point(int x, int y) {
this.x = x;
this.y = y;
}

public Point(String x, String y) {
this.x = Integer.parseInt(x.trim());
this.y = Integer.parseInt(y.trim());
}

public Point(String[] arr) {
this.x = Integer.parseInt(arr[0].trim());
this.y = Integer.parseInt(arr[1].trim());
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
}