-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoint.java
More file actions
74 lines (62 loc) · 1.57 KB
/
Point.java
File metadata and controls
74 lines (62 loc) · 1.57 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
import java.util.Comparator;
import edu.princeton.cs.algs4.StdDraw;
public class Point implements Comparable<Point> {
private int x;
private int y;
// constructs the point (x, y)
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// draws this point
public void draw() {
StdDraw.point(this.x, this.y);
}
// draws the line segment from this point to that point
public void drawTo(Point that) {
StdDraw.line(this.x, this.y, that.x, that.y);
}
// string representation
public String toString() {
String str = "x:" + this.x + " y:" + this.y;
return str;
}
// compare two points by y-coordinates, breaking ties by x-coordinates
public int compareTo(Point that) {
if (this.y > that.y) return 1;
if (this.y < that.y) return -1;
if (this.x > that.x) return 1;
if (this.x < that.x) return -1;
return 0;
}
// the slope between this point and that point
public double slopeTo(Point that) {
if (this.x == that.x && this.y == that.y) {
return Double.NEGATIVE_INFINITY;
} else if (this.x == that.x) {
return Double.POSITIVE_INFINITY;
} else if (this.y == that.y) {
return 0.0;
} else {
return (double)(this.y-that.y)/(this.x - that.x);
}
}
// compare two points by slopes they make with this point
public Comparator<Point> slopeOrder() {
return new MySlopeOrder();
}
private class MySlopeOrder implements Comparator<Point> {
@Override
public int compare(Point o1, Point o2) {
double s1 = slopeTo(o1);
double s2 = slopeTo(o2);
if (s1 < s2) {
return -1;
}
if (s1 > s2){
return 1;
}
return 0;
}
}
}