-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPointSET.java
More file actions
107 lines (77 loc) · 2.63 KB
/
PointSET.java
File metadata and controls
107 lines (77 loc) · 2.63 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
/* *****************************************************************************
* Name:
* Date:
* Description:
**************************************************************************** */
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.SET;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdDraw;
import java.util.Iterator;
public class PointSET {
private SET<Point2D> set;
public PointSET() {
set = new SET<Point2D>();
}
public boolean isEmpty() {
return (this.set.size() == 0);
}
public int size() {
return this.set.size();
}
public void insert(Point2D p) {
if (p == null) throw new java.lang.IllegalArgumentException("null point");
this.set.add(p);
}
public boolean contains(Point2D p) {
if (p == null) throw new java.lang.IllegalArgumentException("null point");
return this.set.contains(p);
}
public void draw() {
StdDraw.enableDoubleBuffering();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
Iterator<Point2D> points;
for (points = set.iterator(); points.hasNext(); ) {
points.next().draw();
}
StdDraw.show();
}
public Iterable<Point2D> range(RectHV rect) {
if (rect == null) {
throw new java.lang.IllegalArgumentException("null input");
}
Stack<Point2D> points = new Stack<Point2D>();
Iterator<Point2D> iter;
for (iter = set.iterator(); iter.hasNext(); ) {
Point2D point = iter.next();
if (point.x() >= rect.xmin() && point.x() <= rect.xmax()) {
if (point.y() >= rect.ymin() && point.y() <= rect.ymax()) {
points.push(point);
}
}
}
return points;
}
public Point2D nearest(Point2D p) {
if (p == null) throw new java.lang.IllegalArgumentException("null point");
Iterator<Point2D> points;
Stack<Point2D> pointStack = new Stack<Point2D>();
double minDist = Double.POSITIVE_INFINITY;
Point2D minPoint = null;
for (points = set.iterator(); points.hasNext(); ) {
pointStack.push(points.next());
}
for (Point2D point : pointStack) {
double distance = Math.pow((point.x() - p.x()), 2) + Math.pow((point.y() - p.y()), 2);
if (distance < minDist) {
minDist = distance;
minPoint = point;
}
}
return minPoint;
}
public static void main(String[] args) {
}
}