Algorithms 第一章1.2

1.2.1 编写一个Point2D实例,从命令行接受一个参数N。在单位正方形中生成N个随机点,然后计算两点之间的最近距离。

public class Test01 {

    public static void main(String[] args) {
        Random r = new Random();
        int N = Integer.parseInt(args[0]);
        Point2D[] arr = new Point2D[N];
        double x = -1, y = -1;
        int count = 0;
        while (count < 4) {
            x = r.nextDouble();
            y = r.nextDouble();
            if (!isExist(x, y, arr)) {
                Point2D point = new Point2D(x, y);
                arr[count++] = point;
            }
        }

        double min = distance(arr[0], arr[1]);
        for (int i = 0; i < N; i++)
            for (int j = i+1; j < N; j++) {
                double d = distance(arr[i], arr[j]);
                if (min > d) min = d;
            }
        System.out.println("minimum distance-->" + min);
    }

    private static boolean isExist(double x, double y, Point2D[] arr) {
        for (Point2D point : arr) {
            if (point != null && point.x == x && point.y == y) return true;
        }
        return false;
    }

    private static double distance(Point2D p1, Point2D p2) {
        return Math.sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
    }

    static class Point2D {
        double x;
        double y;

        public Point2D(double x, double y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "Point2D{" +
                    "x=" + x +
                    ", y=" + y +
                    '}';
        }
    }
}

1.2.2 编写一个Interval1D的用例,从命令行接受一个整数N。此表格标准输入中读取N个间隔(每个间隔由一对double值定义)并打印所有的相交的间隔对。

上一篇:VTK:张量算法Tensor Algorithms


下一篇:Android Fragment