Repository navigation
Expand file tree
/
Copy pathPointSET.java
More file actions
99 lines (82 loc) · 2.12 KB
/
Copy pathPointSET.java
File metadata and controls
99 lines (82 loc) · 2.12 KB
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
99
package kdtrees;
import java.util.ArrayList;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.SET;
public class PointSET {
private SET<Point2D> pointSet;
// construct an empty set of points
public PointSET() {
pointSet = new SET<>();
}
// is the set empty?
public boolean isEmpty() {
return pointSet.isEmpty();
}
// number of points in the set
public int size() {
return pointSet.size();
}
// add the point to the set (if it is not already in the set)
public void insert(Point2D p) {
ArgCkeck(p);
pointSet.add(p);
}
// does the set contain point p?
public boolean contains(Point2D p) {
ArgCkeck(p);
return pointSet.contains(p);
}
// draw all points to standard draw
public void draw() {
for (Point2D point : pointSet) {
point.draw();
}
}
// all points that are inside the rectangle
public Iterable<Point2D> range(RectHV rect) {
ArgCkeck(rect);
ArrayList<Point2D> inPoints = new ArrayList<>();
for (Point2D point : inPoints) {
if(rect.contains(point)){
inPoints.add(point);
}
}
return inPoints;
}
// a nearest neighbor in the set to point p; null if the set is empty
public Point2D nearest(Point2D p) {
ArgCkeck(p);
if(null == pointSet) return null;
Point2D nearest = null;
double lengthMin = 0;
for (Point2D point : pointSet) {
if(null == nearest){
nearest = point;
lengthMin = p.distanceSquaredTo(point);
continue;
}
double distance = p.distanceSquaredTo(point);
if(distance < lengthMin){ lengthMin = distance; nearest = point; }
}
return nearest;
}
private void ArgCkeck(Object obj){
if(null == obj){
throw new NullPointerException();
}
}
// unit testing of the methods (optional)
public static void main(String[] args) {
PointSET set = new PointSET();
set.insert(new Point2D(0.1,0.2));
set.insert(new Point2D(0.2,0.2));
set.insert(new Point2D(0.3,0.2));
set.insert(new Point2D(0.9,0.81));
RectHV rhv = new RectHV(0.4,0.4,0.8,0.8);
rhv.draw();
System.out.println(set.contains(new Point2D(0.3,0.2)));
System.out.println(set.size());
set.draw();
}
}