-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPointSET.java
73 lines (66 loc) · 1.85 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
65
66
67
68
69
70
71
72
73
import java.util.TreeSet;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
public class PointSET {
private TreeSet<Point2D> tree;
public PointSET() // construct an empty set of points
{
tree = new TreeSet<Point2D>();
}
public boolean isEmpty() // is the set empty?
{
return tree.isEmpty();
}
public int size() // number of points in the set
{
return tree.size();
}
public void insert(Point2D p) // add the point to the set (if it is not already in the set)
{
if(p==null) return;
tree.add(p);
}
public boolean contains(Point2D p) // does the set contain point p?
{
return tree.contains(p);
}
public void draw() // draw all points to standard draw
{
StdDraw.setPenRadius(0.01);
for(Point2D p:tree)
{
StdDraw.point(p.x(),p.y());
}
}
public Iterable<Point2D> range(RectHV rect)
// all points that are inside the rectangle (or on the boundary)
{
Queue<Point2D> queue = new Queue<Point2D>();
for(Point2D p:tree)
{
if(rect.contains(p)) queue.enqueue(p);
}
return queue;
}
public Point2D nearest(Point2D p)
// a nearest neighbor in the set to point p; null if the set is empty
{
if(p==null) throw new IllegalArgumentException("Empty point.");
if(tree == null) return null;
double dmin = Double.POSITIVE_INFINITY;
double d = 0;
Point2D minPoint = null;
for(Point2D treePoint: tree)
{
d = p.distanceTo(treePoint);
if(d<dmin)
{
minPoint = treePoint;
dmin = d;
}
}
return minPoint;
}
}