读书笔记《算法》 习题 1.2.1

import java.util.Arrays;

import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;


/**
 * 从命令行接受一个整数N。
 * 在单位正方形内生成N个随机点,然后计算两点之间的最近距离。
 * @author lenovo
 *
 */
public class ShortDistance {

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        Point2D[] p = new Point2D[N];
        
        //生成N个点
        for(int i = 0; i < N; i++) {
            double x = Math.random();
            double y = Math.random();
            p[i] = new Point2D(x,y);
            p[i].draw();
        }
        Arrays.sort(p);
        
        double minDistance = p[0].distanceTo(p[N-1]);
        int minIndex = N;
        
        //比较最小距离
        for(int i = 0; i < N-1; i++) {
            double min = p[i].distanceTo(p[i+1]);
            if(min < minDistance){
                minDistance = min;
                minIndex = i;
            }
        }
        
        StdDraw.setPenColor(StdDraw.RED);  
        //输出
        if(minDistance == N-1){
            p[N-1].drawTo(p[0]);
        }
        else{
            p[minIndex].drawTo(p[minIndex+1]);
        }
        StdOut.print("最小距离为" + minDistance);
        
    }
}

你可能感兴趣的:(读书笔记《算法》 习题 1.2.1)