- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 week
- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 Week
- Princeton Algorithm Part 1 Week
- [Week 2]Princeton Algorithm Part
Point 和LineSegment没有什么好写的,作业大部分已给出。 倒是很好的练习了java的基础。
Point Class:
import java.util.Comparator;
import edu.princeton.cs.algs4.StdDraw;
public class Point implements Comparable<Point> {
private final int x; // x-coordinate of this point
private final int y; // y-coordinate of this point
public Point(int x, int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
public void draw() {
/* DO NOT MODIFY */
StdDraw.point(x, y);
}
public void drawTo(Point that) {
/* DO NOT MODIFY */
StdDraw.line(this.x, this.y, that.x, that.y);
}
public double slopeTo(Point that) {
if (this.x == that.x) {
if (this.y == that.y)
return Double.NEGATIVE_INFINITY;
return Double.POSITIVE_INFINITY;
}
if (this.y == that.y)
return 0;
return (that.y - this.y) / (that.x - this.x);
}
public int compareTo(Point that) {
if (this.x == that.x && this.y == that.y)
return 0;
if (this.y < that.y || this.y == that.y || this.x < that.x)
return -1; // this point is less than that point;
return 1;
}
public String toString() {
/* DO NOT MODIFY */
return "(" + x + ", " + y + ")";
}
public Comparator<Point> slopeOrder() {
return new SlopeComparator();
}
private class SlopeComparator implements Comparator<Point> {
@Override
public int compare(Point o1, Point o2) {
double ox1 = slopeTo(o1);
double ox2 = slopeTo(o2);
if (ox1 < ox2)
return -1;
else if (ox1 > ox2)
return 1;
else
return 0;
}
}
public static void main(String[] args) {
/* YOUR CODE HERE */
}
}
Line segment data type:
public class LineSegment {
private final Point p; // one endpoint of this line segment
private final Point q; // the other endpoint of this line segment
public LineSegment(Point p, Point q) {
if (p == null || q == null) {
throw new NullPointerException("argument is null");
}
this.p = p;
this.q = q;
}
public void draw() {
p.drawTo(q);
}
public String toString() {
return p + " -> " + q;
}
public int hashCode() {
throw new UnsupportedOperationException();
}
}
网友评论