Contains.java


Below is the syntax highlighted version of Contains.java from §2.1 Static Methods.


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


public class Contains {

    // draw the circles
    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) contain circle (x2, y2, r2) ?
    public static boolean contains(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(0.5, 0.5, 0.5);
        StdDraw.setPenColor(StdDraw.GRAY);
        drawCircles(x, y, r);

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

        // print and plot the circle that contains the most other circles
        StdOut.println("contains = " + maxContains);
        StdDraw.setPenRadius(0.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 © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:15:13 EDT 2022.