01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package algs12;
import stdlib.*;
/* ***********************************************************************
* Compilation: javac Interval2D.java
* Execution: java Interval2D
*
* 2-dimensional interval data type.
*
*************************************************************************/
public class Interval2D {
private final Interval1D x;
private final Interval1D y;
public Interval2D(Interval1D x, Interval1D y) {
this.x = x;
this.y = y;
}
// does this interval intersect that one?
public boolean intersects(Interval2D that) {
if (!this.x.intersects(that.x)) return false;
if (!this.y.intersects(that.y)) return false;
return true;
}
// does this interval contain x?
public boolean contains(Point2D p) {
return x.contains(p.x()) && y.contains(p.y());
}
// area of this interval
public double area() {
return x.length() * y.length();
}
public String toString() {
return x + " x " + y;
}
public void draw() {
double xc = (x.left() + x.right()) / 2.0;
double yc = (y.left() + y.right()) / 2.0;
StdDraw.rectangle(xc, yc, x.length() / 2.0, y.length() / 2.0);
}
// test client
public static void main(String[] args) {
args = new String[] { ".3", ".4", ".5", ".6", "1000" };
double xlo = Double.parseDouble(args[0]);
double xhi = Double.parseDouble(args[1]);
double ylo = Double.parseDouble(args[2]);
double yhi = Double.parseDouble(args[3]);
int T = Integer.parseInt(args[4]);
Interval1D xinterval = new Interval1D(xlo, xhi);
Interval1D yinterval = new Interval1D(ylo, yhi);
Interval2D box = new Interval2D(xinterval, yinterval);
box.draw();
Counter counter = new Counter("hits");
for (int t = 0; t < T; t++) {
double x = StdRandom.random();
double y = StdRandom.random();
Point2D p = new Point2D(x, y);
if (box.contains(p)) counter.increment();
else p.draw();
}
StdOut.println(counter);
StdOut.format("box area = %.2f\n", box.area());
}
}
|