代码:https://github.com/RedemptionC/CourseraAlgorithms/tree/master/collinear
这是学完归并排序和快速排序之后的编程作业,需要提交3个类:BruteCollinearPoints.java
,FastCollinearPoints.java
和Point.java
在本文最后,会附上对课堂上教过的排序算法的总结
问题描述很简单:给出一系列的点,将其中包含四个点以上的最大线段找出来
这里的最大是指,如果一条线段包含五个点,那么就不要它包含四个点的现段
Point
需要为point类补上三个方法:
compareTo
即比较两个点,按要求,首先比较y,如果相等,再比较x
public int compareTo(Point that) {
/* YOUR CODE HERE */
if (this.y == that.y) {
return this.x - that.x;
}
else {
return this.y - that.y;
}
}
slopeTo
即返回两点之间连线的斜率:特殊情况下应该返回什么,注释已经写清楚了
/**
* Returns the slope between this point and the specified point.
* Formally, if the two points are (x0, y0) and (x1, y1), then the slope
* is (y1 - y0) / (x1 - x0). For completeness, the slope is defined to be
* +0.0 if the line segment connecting the two points is horizontal;
* Double.POSITIVE_INFINITY if the line segment is vertical;
* and Double.NEGATIVE_INFINITY if (x0, y0) and (x1, y1) are equal.
*
* @param that the other point
* @return the slope between this point and the specified point
*/
public double slopeTo(Point that) {
/* YOUR CODE HERE */
if (that.x == this.x && that.y == this.y)
return Double.NEGATIVE_INFINITY;
if (that.x == this.x)
return Double.POSITIVE_INFINITY;
if (that.y == this.y)
return +0.0;
return (double) (that.y - this.y) / (that.x - this.x);
}
slopeOrder
这里要返回一个comparator,用来比较两个点,比较依据是和当前点连线的斜率
private class bySlope implements Comparator<Point> {
public int compare(Point o1, Point o2) {
double slope1 = Point.this.slopeTo(o1);
double slope2 = Point.this.slopeTo(o2);
if (slope1 > slope2)
return 1;
else if (slope1 < slope2)
return -1;
else
return 0;
}
}
/**
* Compares two points by the slope they make with this point.
* The slope is defined as in the slopeTo() method.
*
* @return the Comparator that defines this ordering on points
*/
public Comparator<Point> slopeOrder() {
/* YOUR CODE HERE */
return new bySlope();
}
BruteCollinearPoints
这里要使用暴力法作答,并且题目里指出了,暴力法不会用来处理五个及五个点以上的共线
具体做法是,首先对所有的点排序,因为point实现了comparable接口,所以Arrays.sort会使用point的compareTo进行排序
然后用四层循环,检查后三个点和第一个点的连线斜率是否相同,如果是,就加入结果集
public BruteCollinearPoints(Point[] tpo