Intersects.java


Below is the syntax highlighted version of Intersects.java.


/*************************************************************************
 *  Compilation:  javac Intersects.java
 *  Execution:    java Intersects < input.txt
 *  Dependencies: StdDraw.java StdIn.java StdOut.java
 *
 *  Reads in an integer N, followed by N circles (xi, yi, ri) from
 *  standard input; plot them to standard draw; computes the circle
 *  that intersects the most other circles; plots that circle in red;
 *  prints that circle to standard output; and prints the number
 *  of other circles it intersects.
 *
 *************************************************************************/


public class Intersects {

    // draw the circles to standard draw
    public static void drawCircles(double[] x, double[] y, double[] r) {
        int N = x.length;
        for (int i = 0; i < N; i++) {
            StdDraw.circle(x[i], y[i], r[i]);
        }
    }

    // does circle (x1, y1, r1) intersect circle (x2, y2, r2)?
    public static boolean intersects(double x1, double y1, double r1,
                                     double x2, double y2, double r2) {
        double dx = x1 - x2;
        double dy = y1 - y2;
        double distance = Math.sqrt(dx*dx + dy*dy);
        return distance <= r1 + r2;
    }


    public static void main(String[] args) { 

        // read in the data
        int N = StdIn.readInt();
        double[] x = new double[N];
        double[] y = new double[N];
        double[] r = new double[N];
        for (int i = 0; i < N; i++) {
            x[i] = StdIn.readDouble();
            y[i] = StdIn.readDouble();
            r[i] = StdIn.readDouble();
        }

        // draw the circles
        StdDraw.clear(StdDraw.GRAY);
        StdDraw.setPenColor(StdDraw.WHITE);
        StdDraw.filledSquare(.5, .5, .5);
        StdDraw.setPenColor(StdDraw.GRAY);
        drawCircles(x, y, r);

        // compute circle that intersects the most other circles
        int maxIntersects = -1;
        int max = -1;
        for (int i = 0; i < N; i++) {
            int intersects = 0;
            for (int j = 0; j < N; j++) {
                if ((i != j) && (intersects(x[i], y[i], r[i], x[j], y[j], r[j])))
                    intersects++;
            }
            if (intersects > maxIntersects) {
                maxIntersects = intersects;
                max = i;
            }
        }

        // print and plot the circle that intersects the most other circles
        StdOut.println("intersections = " + maxIntersects);
        // StdDraw.setPenRadius(.004);
        StdDraw.setPenColor(StdDraw.RED);
        if (max >= 0) {
            StdDraw.circle(x[max], y[max], r[max]);
            StdOut.println("(" + x[max] + "," + y[max] + "," + r[max] + ")");
        }
    }
}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Mon Mar 23 09:51:49 EDT 2009.