PointSET.java
2.09 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
100
101
102
103
104
105
106
107
108
import java.io.BufferedReader;
import java.io.FileReader;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.SET;
public class PointSET {
private SET<Point2D> points;
// construct an empty set of points
public PointSET() {
this.points = new SET<Point2D>();
}
// is the set empty?
public boolean isEmpty() {
return points.isEmpty();
}
// number of points in the set
public int size() {
return points.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 NullPointerException();
if (!points.contains(p)) {
points.add(p);
}
}
// does the set contain point p?
public boolean contains(Point2D p) {
if(p == null)
throw new NullPointerException();
return points.contains(p);
}
// draw all points to standard draw
public void draw() {
for (Point2D p : points) {
p.draw();
}
}
// all points that are inside the rectangle
public Iterable<Point2D> range(RectHV rect) {
SET<Point2D> contains = new SET<Point2D>();
for (Point2D p : points) {
if (rect.contains(p)) {
contains.add(p);
}
}
return contains;
}
// a nearest neighbor in the set to point p; null if the set is empty
public Point2D nearest(Point2D p) {
Point2D closest = null;
for (Point2D point : points) {
if (closest == null || p.distanceTo(point) < p.distanceTo(closest)) {
closest = p;
}
}
return closest;
}
// unit testing of the methods (optional)
public static void main(String[] args) throws Exception{
PointSET set = new PointSET();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(args[0]));
} catch (Exception e) {
System.out.println("File not found");
}
String line;
while((line = reader.readLine()) != null){
String [] splitLine = line.trim().split("\\s+");
double a = Double.parseDouble(splitLine[0]);
double b = Double.parseDouble(splitLine[1]);
Point2D p = new Point2D(a,b);
set.insert(p);
}
set.draw();
}
}