-
Notifications
You must be signed in to change notification settings - Fork 0
/
BruteCollinearPoints.java
92 lines (79 loc) · 2.87 KB
/
BruteCollinearPoints.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
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
public class BruteCollinearPoints {
private int n = 0;
private Queue<LineSegment> segments = new Queue<>();
public BruteCollinearPoints(Point[] points) {
if (points == null) throw new IllegalArgumentException("");
for (Point p : points)
if (p == null) throw new IllegalArgumentException("");
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
for (int k = j + 1; k < points.length; k++) {
for (int m = k + 1; m < points.length; m++) {
if (points[i].slopeTo(points[j]) ==
points[j].slopeTo(points[k]) &&
points[j].slopeTo(points[k]) ==
points[k].slopeTo(points[m])) {
Point[] arr = {
points[i], points[j],
points[k], points[m]
};
Arrays.sort(arr);
checkEnqueue(new LineSegment(arr[0], arr[3]));
}
}
}
}
}
} // finds all line segments containing 4 points
private void checkEnqueue(LineSegment segment) {
for (LineSegment seg : segments) {
if (seg.toString().equals(segment.toString())) {
return;
}
}
n++;
segments.enqueue(segment);
}
public int numberOfSegments() {
return n;
} // the number of line segments
public LineSegment[] segments() {
LineSegment[] arr = new LineSegment[n];
int index = 0;
for (LineSegment sg : segments) {
arr[index++] = sg;
}
return arr;
} // the line segments
public static void main(String[] args) {
// read the n points from a file
In in = new In(args[0]);
int n = in.readInt();
Point[] points = new Point[n];
for (int i = 0; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
}
// draw the points
StdDraw.enableDoubleBuffering();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
for (Point p : points) {
p.draw();
}
StdDraw.show();
// print and draw the line segments
BruteCollinearPoints collinear = new BruteCollinearPoints(points);
for (LineSegment segment : collinear.segments()) {
StdOut.println(segment);
segment.draw();
}
StdDraw.show();
}
}