001package algs12; 002import stdlib.*; 003 004/* *********************************************************************** 005 * Compilation: javac Interval2D.java 006 * Execution: java Interval2D 007 * 008 * 2-dimensional interval data type. 009 * 010 *************************************************************************/ 011 012public class Interval2D { 013 private final Interval1D x; 014 private final Interval1D y; 015 016 public Interval2D(Interval1D x, Interval1D y) { 017 this.x = x; 018 this.y = y; 019 } 020 021 // does this interval intersect that one? 022 public boolean intersects(Interval2D that) { 023 if (!this.x.intersects(that.x)) return false; 024 if (!this.y.intersects(that.y)) return false; 025 return true; 026 } 027 028 // does this interval contain x? 029 public boolean contains(Point2D p) { 030 return x.contains(p.x()) && y.contains(p.y()); 031 } 032 033 // area of this interval 034 public double area() { 035 return x.length() * y.length(); 036 } 037 038 public String toString() { 039 return x + " x " + y; 040 } 041 042 public void draw() { 043 double xc = (x.left() + x.right()) / 2.0; 044 double yc = (y.left() + y.right()) / 2.0; 045 StdDraw.rectangle(xc, yc, x.length() / 2.0, y.length() / 2.0); 046 } 047 048 // test client 049 public static void main(String[] args) { 050 args = new String[] { ".3", ".4", ".5", ".6", "1000" }; 051 052 double xlo = Double.parseDouble(args[0]); 053 double xhi = Double.parseDouble(args[1]); 054 double ylo = Double.parseDouble(args[2]); 055 double yhi = Double.parseDouble(args[3]); 056 int T = Integer.parseInt(args[4]); 057 058 Interval1D xinterval = new Interval1D(xlo, xhi); 059 Interval1D yinterval = new Interval1D(ylo, yhi); 060 Interval2D box = new Interval2D(xinterval, yinterval); 061 box.draw(); 062 063 Counter counter = new Counter("hits"); 064 for (int t = 0; t < T; t++) { 065 double x = StdRandom.random(); 066 double y = StdRandom.random(); 067 Point2D p = new Point2D(x, y); 068 069 if (box.contains(p)) counter.increment(); 070 else p.draw(); 071 } 072 073 StdOut.println(counter); 074 StdOut.format("box area = %.2f\n", box.area()); 075 } 076}