MCPcopy Create free account
hub / github.com/MolinDeng/Princeton-algs4 / PointSET

Class PointSET

05Lab-Kd Tree/PointSET.java:15–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13import java.util.TreeSet;
14
15public class PointSET {
16 private TreeSet<Point2D> treeSet;
17
18 // construct an empty set of points
19 public PointSET() {
20 treeSet = new TreeSet<>();
21 }
22
23 // is the set empty?
24 public boolean isEmpty() {
25 return treeSet.isEmpty();
26 }
27
28 // number of points in the set
29 public int size() {
30 return treeSet.size();
31 }
32
33 // add the point to the set (if it is not already in the set)
34 public void insert(Point2D p) {
35 if (p == null) throw new IllegalArgumentException();
36 treeSet.add(p);
37 }
38
39 // does the set contain point p?
40 public boolean contains(Point2D p) {
41 if (p == null) throw new IllegalArgumentException();
42 return treeSet.contains(p);
43 }
44
45 // draw all points to standard draw
46 public void draw() {
47 StdDraw.setPenColor(StdDraw.BLACK);
48 // StdDraw.setPenRadius(0.01);
49 for (Point2D p : treeSet)
50 StdDraw.point(p.x(), p.y());
51 }
52
53 // all points that are inside the rectangle (or on the boundary)
54 public Iterable<Point2D> range(RectHV rect) {
55 if (rect == null) throw new IllegalArgumentException();
56 ArrayList<Point2D> arrayList = new ArrayList<>();
57 for (Point2D p : treeSet)
58 if (rect.contains(p)) arrayList.add(p);
59 return arrayList;
60 }
61
62 // a nearest neighbor in the set to point p; null if the set is empty
63 public Point2D nearest(Point2D p) {
64 if (p == null) throw new IllegalArgumentException();
65 double min = Double.POSITIVE_INFINITY;
66 Point2D champion = null;
67 for (Point2D i : treeSet) {
68 double d = p.distanceSquaredTo(i);
69 if (d < min) {
70 min = d;
71 champion = i;
72 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected