Created
November 17, 2016 13:33
-
-
Save Gummary/7d4ddbd9d143f632f1b319035f4c5d15 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import edu.princeton.cs.algs4.*; | |
public class BruteCollinearPoints { | |
private ArrayList<LineSegment> segs; | |
public BruteCollinearPoints(Point[] points) { | |
if (points == null) { | |
throw new java.lang.NullPointerException(); | |
} | |
Point[] copyPoints = Arrays.copyOf(points, points.length); | |
Arrays.sort(copyPoints); | |
checkDuplicatePoints(copyPoints); | |
segs = new ArrayList<LineSegment>(); | |
for (int i = 0; i < copyPoints.length - 3; i++) { | |
Point p = copyPoints[i]; | |
if (p == null) { | |
throw new java.lang.NullPointerException(); | |
} | |
for (int j = i + 1; j < copyPoints.length - 2; j++) { | |
Point q = copyPoints[j]; | |
if (q == null) { | |
throw new java.lang.NullPointerException(); | |
} | |
for (int k = j + 1; k < copyPoints.length - 1; k++) { | |
Point r = copyPoints[k]; | |
if (r == null) { | |
throw new java.lang.NullPointerException(); | |
} | |
for (int l = k + 1; l < copyPoints.length; l++) { | |
Point s = copyPoints[l]; | |
if (s == null) { | |
throw new java.lang.NullPointerException(); | |
} | |
double pq = p.slopeTo(q); | |
double pr = p.slopeTo(r); | |
double ps = p.slopeTo(s); | |
if (pq == pr && pq == ps && pr == ps) { | |
segs.add(new LineSegment(p, s)); | |
} | |
} | |
} | |
} | |
} | |
} | |
private void checkDuplicatePoints(Point[] points) { | |
for (int i = 1; i < points.length; i++) { | |
if (points[i].compareTo(points[i - 1]) == 0) { | |
throw new java.lang.IllegalArgumentException(); | |
} | |
} | |
} | |
public int numberOfSegments() { | |
return segs.size(); | |
} | |
public LineSegment[] segments() { | |
return segs.toArray(new LineSegment[segs.size()]); | |
} | |
public static void main(String[] args) { | |
// read the n points from a file | |
String s = "/home/hepeng/Algorithm(4th)/Coursera/Collinear Points/collinear/repeat"; | |
In in = new In(s); | |
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment