-
Notifications
You must be signed in to change notification settings - Fork 24
/
FastCollinearPoints.java
89 lines (82 loc) · 2.37 KB
/
FastCollinearPoints.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
package three;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author sunyue
* @version 1.0 2017/1/13 12:49
*/
public class FastCollinearPoints {
private LineSegment[] ls;
/**
* finds all line segments containing 4 or more points
*
* @param points
*/
public FastCollinearPoints(Point[] points) {
// Corner cases
if (points == null) throw new NullPointerException("argument is null");
int n = points.length;
for (int i = 0; i < n; i++) {
if (points[i] == null) throw new NullPointerException("array contains null point");
for (int j = i + 1; j < n; j++) {
if (points[i].compareTo(points[j]) == 0)
throw new IllegalArgumentException("array contains a repeated point");
}
}
Point[] ps = points.clone();
Arrays.sort(ps);
List<LineSegment> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
Point[] p = ps.clone();
Arrays.sort(p, p[i].slopeOrder());
int j = 1;
while (j < n - 2) {
int k = j;
double s1 = p[0].slopeTo(p[k++]);
double s2;
do {
if (k == n) {
k++;
break;
}
s2 = p[0].slopeTo(p[k++]);
} while (s1 == s2);
if (k - j < 4) {
j++;
continue;
}
int len = k-- - j;
Point[] line = new Point[len];
line[0] = p[0];
for (int l = 1; l < len; l++) {
line[l] = p[j + l - 1];
}
Arrays.sort(line);
// remove duplicate
if (line[0] == p[0]) {
list.add(new LineSegment(line[0], line[len - 1]));
}
j = k;
}
}
// transform to array
ls = list.toArray(new LineSegment[list.size()]);
}
/**
* the number of line segments
*
* @return
*/
public int numberOfSegments() {
return ls.length;
}
/**
* the line segments
*
* @return
*/
public LineSegment[] segments() {
return ls.clone();
}
}