第三周作业模式识别
Programming Assignment 3: Pattern Recognition
题目地址:http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
------------------------------------------
这一周的问题是在一个给出N个随即点的平面上,画出所有所在路径超过四个点的直线。
首先还是老老实实的从第一个类开始说起。
public class Point implements Comparable<Point> {
public final Comparator<Point> SLOPE_ORDER; // compare points by slope to this point
public Point(int x, int y) // construct the point (x, y)
public void draw() // draw this point
public void drawTo(Point that) // draw the line segment from this point to that point
public String toString() // string representation
public int compareTo(Point that) // is this point lexicographically smaller than that point?
public double slopeTo(Point that) // the slope between this point and that point
}
第一个类的主要功能是创建点的分布,并通过StdDraw类输出,其中运用到了比较器。
很良心的,其中前四个方法已经给出。
我们只需要把后两个和比较器写出。
1. public int compareTo(Point that) // is this point lexicographically smaller than that point?
也就是是否这个点是否比那个点小,比较标准给出了,
y0<y1或y0=y1但x0<x1时 表示this.point<that.point
2.public double slopeTo(Point that) // the slope between this point and that point
计算两点间斜率,官方说明上给的很清楚,包括各类情况的返回值,就不多说了。
3.public final Comparator<Point> SLOPE_ORDER;
用来比较斜率的比较器,第一次用不是很会用。后来摸透了以后感觉很方便。
代码如下:
import java.util.Comparator;
public class Point implements Com