-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPointSET.java
98 lines (97 loc) · 3.03 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/******************************************************************************
* Compilation: javac-algs4 PointSET.java
* Execution: java-algs4 PointSET
* Dependencies:
*
*
******************************************************************************/
import edu.princeton.cs.algs4.SET;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.StdOut;
public class PointSET {
private final SET<Point2D> set;
// construct an empty set of points
public PointSET() {
set = new SET<>();
}
// 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 to the set (if it is not already in the set)
public void insert(Point2D p) {
if (p == null) {
throw new IllegalArgumentException();
}
else if (!set.contains(p)) {
set.add(p);
}
}
// does the set contain point p?
public boolean contains(Point2D p) {
if (p == null) {
throw new IllegalArgumentException();
}
else {
return set.contains(p);
}
}
// draw all points to standard draw
public void draw() {
for (Point2D point:set) {
point.draw();
}
}
// all points that are inside the rectangle (or on the boundary)
public Iterable<Point2D> range(RectHV rect) {
if (rect == null) {
throw new IllegalArgumentException();
}
else {
Stack<Point2D> points = new Stack<>();
for (Point2D point:set) {
if (rect.contains(point)) {
points.push(point);
}
}
return points;
}
}
// a nearest neighbor in the set to point p; null if the set is empty
public Point2D nearest(Point2D p) {
if (p == null) {
throw new IllegalArgumentException();
}
else if (set.isEmpty()) {
return null;
}
else {
double nearestDistance = Double.POSITIVE_INFINITY;
Point2D nearestPoint = null;
for (Point2D point:set) {
double distance = point.distanceSquaredTo(p);
if (distance < nearestDistance) {
nearestPoint = point;
nearestDistance = distance;
}
}
return nearestPoint;
}
}
// unit testing of the methods (optional)
public static void main(String[] args) {
PointSET points = new PointSET();
points.insert(new Point2D(0.7, 0.2));
points.insert(new Point2D(0.5, 0.4));
points.insert(new Point2D(0.2, 0.3));
points.insert(new Point2D(0.4, 0.7));
points.insert(new Point2D(0.9, 0.6));
StdOut.println(points.nearest(new Point2D(1.0, 1.0)).x() + " " + points.nearest(new Point2D(1.0, 1.0)).y());
}
}