The problem. Given a set of N distinct points in the plane, draw every (maximal) line segment that connects a subset of 4 or more of the points.

Point data type. Create an immutable data type Point that represents a point in the plane by implementing the following API:

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 }

To get started, use the data type Point.java, which implements the constructor and the draw(), drawTo(), and toString() methods. Your job is to add the following components.

  • The compareTo() method should compare points by their y-coordinates, breaking ties by their x-coordinates. Formally, the invoking point (x0, y0) is less than the argument point (x1, y1) if and only if either y0 < y1 or if y0 = y1 and x0 < x1.
  • The slopeTo() method should return the slope between the invoking point (x0, y0) and the argument point (x1, y1), which is given by the formula (y1y0) / (x1x0). Treat the slope of a horizontal line segment as positive zero; treat the slope of a vertical line segment as positive infinity; treat the slope of a degenerate line segment (between a point and itself) as negative infinity.
  • The SLOPE_ORDER comparator should compare points by the slopes they make with the invoking point (x0, y0). Formally, the point (x1, y1) is less than the point (x2,y2) if and only if the slope (y1y0) / (x1x0) is less than the slope (y2y0) / (x2x0). Treat horizontal, vertical, and degenerate line segments as in the slopeTo() method.
import java.util.Comparator;

public class Point implements Comparable<Point> {

 public final Comparator<Point> SLOPE_ORDER = new PointCmp();

 private final int x; // x coordinate
private final int y; // y coordinate 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) {
/* YOUR CODE HERE */
if (this.compareTo(that) == 0)
return Double.POSITIVE_INFINITY*-1;
else if (this.x == that.x)
return Double.POSITIVE_INFINITY;
else if (this.y == that.y)
return +0;
else
return (that.y - this.y) * 1.0 / (that.x - this.x);
} private class PointCmp implements Comparator<Point> { @Override
public int compare(Point o1, Point o2) {
// TODO Auto-generated method stub
if (slopeTo(o1) < slopeTo(o2) || (slopeTo(o1) == slopeTo(o2) && o1.compareTo(o2) == -1))
return -1;
else if (slopeTo(o1) > slopeTo(o2) || (slopeTo(o1) == slopeTo(o2) && o1.compareTo(o2) == 1))
return 1;
else
return 0;
} } @Override
public int compareTo(Point that) {
// TODO Auto-generated method stub
if (this.y < that.y || (this.y == that.y && this.x < that.x))
return -1;
else if (this.y == that.y && this.x == that.x)
return 0;
else
return 1;
} public String toString() {
/* DO NOT MODIFY */
return "(" + x + ", " + y + ")";
} public static void main(String[] args) {
// TODO Auto-generated method stub
In in = new In(args[0]);
int num = in.readInt();
Point points[] = new Point[num];
for (int i = 0; i < num; i++) {
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
} } }

Brute force. Write a program Brute.java that examines 4 points at a time and checks whether they all lie on the same line segment, printing out any such line segments to standard output and drawing them using standard drawing. To check whether the 4 points p, q, r, and s are collinear, check whether the slopes between p and q, between p and r, and between p and s are all equal.

The order of growth of the running time of your program should be N4 in the worst case and it should use space proportional to N.

public class Brute {
public static void main(String[] args) {
// rescale coordinates and turn on animation mode
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
StdDraw.show(0);
StdDraw.setPenRadius(0.01); // make the points a bit larger // read in the input
String filename = args[0];
In in = new In(filename);
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);
points[i].draw();
} for (int i = 0; i < N; i++) {
for (int j = 0; j < N - i - 1; j++) {
if (points[j].compareTo(points[j+1]) == 1) {
Point temp = points[j];
points[j] = points[j + 1];
points[j + 1] = temp;
}
}
} for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
for (int k = j + 1; k < N; k++) {
for(int l = k + 1; l < N; l++) {
if(points[i].slopeTo(points[j]) == points[j].slopeTo(points[k])&&
points[j].slopeTo(points[k]) == points[k].slopeTo(points[l])) {
points[i].drawTo(points[l]);
StdOut.print(points[i].toString()+" -> "+points[j].toString()
+" -> "+points[k].toString()+" -> "+points[l].toString());
StdOut.println();
} }
}
}
} // display to screen all at once
StdDraw.show(0); // reset the pen radius
StdDraw.setPenRadius();
}
}

A faster, sorting-based solution. Remarkably, it is possible to solve the problem much faster than the brute-force solution described above. Given a point p, the following method determines whether p participates in a set of 4 or more collinear points.

  • Think of p as the origin.
  • For each other point q, determine the slope it makes with p.
  • Sort the points according to the slopes they makes with p.
  • Check if any 3 (or more) adjacent points in the sorted order have equal slopes with respect to p. If so, these points, together with p, are collinear.

Applying this method for each of the N points in turn yields an efficient algorithm to the problem. The algorithm solves the problem because points that have equal slopes with respect to p are collinear, and sorting brings such points together. The algorithm is fast because the bottleneck operation is sorting.

Write a program Fast.java that implements this algorithm. The order of growth of the running time of your program should be N2 log N in the worst case and it should use space proportional to N.

源代码待补;

Programming Assignment 3: Collinear Points的更多相关文章

  1. 课程一(Neural Networks and Deep Learning),第三周(Shallow neural networks)—— 3.Programming Assignment : Planar data classification with a hidden layer

    Planar data classification with a hidden layer Welcome to the second programming exercise of the dee ...

  2. Algorithms : Programming Assignment 3: Pattern Recognition

    Programming Assignment 3: Pattern Recognition 1.题目重述 原题目:Programming Assignment 3: Pattern Recogniti ...

  3. Algorithms: Design and Analysis, Part 1 - Programming Assignment #1

    自我总结: 1.编程的思维不够,虽然分析有哪些需要的函数,但是不能比较好的汇总整合 2.写代码能力,容易挫败感,经常有bug,很烦心,耐心不够好 题目: In this programming ass ...

  4. Programming Assignment 5: Kd-Trees

    用2d-tree数据结构实现在2维矩形区域内的高效的range search 和 nearest neighbor search.2d-tree有许多的应用,在天体分类.计算机动画.神经网络加速.数据 ...

  5. Programming Assignment 2: Randomized Queues and Deques

    实现一个泛型的双端队列和随机化队列,用数组和链表的方式实现基本数据结构,主要介绍了泛型和迭代器. Dequeue. 实现一个双端队列,它是栈和队列的升级版,支持首尾两端的插入和删除.Deque的API ...

  6. 课程一(Neural Networks and Deep Learning),第二周(Basics of Neural Network programming)—— 2、编程作业常见问题与答案(Programming Assignment FAQ)

    Please note that when you are working on the programming exercise you will find comments that say &q ...

  7. Programming Assignment 3: Pattern Recognition

    编程作业三 作业链接:Pattern Recognition & Checklist 我的代码:BruteCollinearPoints.java & FastCollinearPoi ...

  8. Programming Assignment 4: Boggle

    编程作业四 作业链接:Boggle & Checklist 我的代码:BoggleSolver.java 问题简介 Boggle 是一个文字游戏,有 16 个每面都有字母的骰子,开始随机将它们 ...

  9. Coursera Algorithms Programming Assignment 3: Pattern Recognition (100分)

    题目原文详见http://coursera.cs.princeton.edu/algs4/assignments/collinear.html 程序的主要目的是寻找n个points中的line seg ...

随机推荐

  1. 仿酷狗音乐播放器开发日志二十五 duilib右键事件的不足的bug修复

    转载请说明原出处,谢谢~~ 虽然仿酷狗的各个菜单早就写好了,但是一直没有附加到程序里.今天把菜单和播放列表控件关联时发现了问题. 和播放列表相关的菜单有三个,分别是每个音乐项目控件相关的菜单.分组的菜 ...

  2. 你认为你很了解Javascript?

    (翻译不当之处请谅解) 来源:http://www.ido321.com/914.html 这里有5个小脚本,有助于你真正理解JavaScript核心–闭包和作用域.没有在控制台运行之前,尝试回答每个 ...

  3. WCF启用Session

    1 服务类添加ASPNETSESSION兼容标记 [System.ServiceModel.Activation.AspNetCompatibilityRequirements(Requirement ...

  4. 最短路径算法(Dijkstra算法、Floyd-Warshall算法)

    最短路径算法具体的形式包括: 确定起点的最短路径问题:即已知起始结点,求最短路径的问题.适合使用Dijkstra算法. 确定终点的最短路径问题:即已知终结结点,求最短路径的问题.在无向图中,该问题与确 ...

  5. Windows server 2008 上部署 MVC (NopCommerce 3.4)网站

    自己用开源框架做了个商城,该框架是基于mvc4的,本地编译通过,运行一切正常,关于发布遇到了好几个问题. 本地: IIS7.5. VS2013 总结后发现只需要设置两个问题,就不会有那些古怪的问题:什 ...

  6. Trail: JDBC(TM) Database Access(1)

    package com.oracle.tutorial.jdbc; import java.sql.BatchUpdateException; import java.sql.Connection; ...

  7. Hadoop在百度的应用

    百度作为全球最大的中文搜索引擎公司,提供基于搜索引擎的各种产品,包括以网络搜索为主的功能性搜索:以贴吧为主的社区搜索:针对区域.行业的垂直搜索.MP3音乐搜索,以及百科等,几乎覆盖了中文网络世界中所有 ...

  8. redis的string类型

    string : string类型是二进制安全的, 可以包含任何数据,比如jpg图片或者序列化的对象 . 方法 : set : 设置key对应的值为string类型的value set  name   ...

  9. work_6

    这次的作业是阅读C++11的新特性并提出问题,作为一个大部分代码都是用C++的基本语法并没有特别关注C++一代又一代新特性的学生来说,首先我阅读了一些关于新特性的文章.为了更快的理解,我首先选择了阅读 ...

  10. I - Control - HDU 4289 (最大流)

    题意:有N个城市,现在城市S出现了一伙歹徒,他们想运送一些炸弹到D城市,不过警方已经得到了线报知道他们的事情,不过警察不知道他们所在的具体位置,所以只能采取封锁城市的办法来阻断暴徒,不过封锁城市是需要 ...