-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPointSET.java
64 lines (47 loc) · 1.65 KB
/
PointSET.java
1
2
3
4
5
6
7
8
9
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
public class PointSET {
private SET<Point2D> set;
// construct an empty set of points
public PointSET() { set = new SET<Point2D>(); }
// is the set empty?
public boolean isEmpty() { return set.isEmpty(); }
// number of points in the set
public int size() { return set.size(); }
// add the point p to the set (if it is not already in the set)
// proportional to logarithm of N in the worst case
public void insert(Point2D p) { set.add(p); }
// does the set contain the point p?
// proportional to logarithm of N in the worst case
public boolean contains(Point2D p) { return set.contains(p); }
// draw all of the points to standard draw
public void draw() {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(.01);
for (Point2D p : set)
StdDraw.point(p.x(), p.y());
StdDraw.show(0);
}
// all points in the set that are inside the rectangle
// proportional to N in the worst case
public Iterable<Point2D> range(RectHV rect) {
Stack<Point2D> s = new Stack<Point2D>();
for (Point2D p : set)
if (rect.contains(p))
s.push(p);
return s;
}
// a nearest neighbor in the set to p: null if set is empty
// proportional to N
public Point2D nearest(Point2D p) {
if (isEmpty()) return null;
double dis, minDis = Double.MAX_VALUE;
Point2D q = null;
for (Point2D ip : set) {
dis = p.distanceSquaredTo(ip);
if (dis < minDis) {
minDis = dis;
q = ip;
}
}
return q;
}
}