import java.awt.*;
import java.util.HashSet;
import java.util.Random;
class example2 {
private static Point[] mTestPoints;
//已知平面上N点坐标,求遍历所有点的最短路径.
public static void main(String[] args) {
//两点之间的距离 d=√(a^2+b^2) 其中a=|x1 –x2|;b=|y1 - y2|
//都是简单的正相关函数,距离最短那么需要a+b最小
//n个点需要求C(n,2)次
//其实java提供了两点之间距离的Api咱们直接使用即可
generateTestPoints();
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < mTestPoints.length; i++) {
//两两计算,数组中每个点只跟后面的点求距离
for (int j = i + 1; j < mTestPoints.length; j++) {
double distance = mTestPoints[i].distance(mTestPoints[j]);
if (distance < minDistance) {
minDistance = distance;
}
}
}
//得到结果
System.out.println("最短距离为:" + minDistance);
}
private static void generateTestPoints() {
//随机生成10个点的集合,为了去重使用hashSet
Random random = new Random();
HashSet mPointSet = new HashSet<>();
for (int i = 0; i < 10; i++) {
boolean add = mPointSet.add(new Point(random.nextInt(100), random.nextInt(100)));
if (!add) {
--i;
}
}
mTestPoints = mPointSet.toArray(new Point[10]);
}
}