Algorithm Part I:Programming Assignment(3)

问题描述:

Programming Assignment 3: Pattern Recognition

Write a program to recognize line patterns in a given set of points.

Computer vision involves analyzing patterns in visual images and reconstructing the real-world objects that produced them. The process in often broken up into two phases: feature detection and pattern
recognition
. Feature detection involves selecting important features of the image; pattern recognition involves discovering patterns in the features. We will investigate a particularly clean pattern recognition problem involving points and line segments.
This kind of pattern recognition arises in many other applications such as statistical data analysis.

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 (x0y0) is less than the argument point
    (x1y1) if and only if eithery0 < y1 or if y0 = y1 and x0 < x1.
  • The slopeTo() method should return the slope between the invoking point (x0y0) and the argument point (x1y1), which is given by the formula (y1 ? y0)
    / (x1 ? x0). 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 (x0y0). Formally, the point (x1y1) is less than the point
    (x2y2) if and only if the slope (y1 ? y0) / (x1 ? x0) is less than the slope (y2 ? y0) / (x2 ? x0).
    Treat horizontal, vertical, and degenerate line segments as in the slopeTo() method.

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 pqr, 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.

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 pparticipates 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.

APIs. Each program should take the name of an input file as a command-line argument, read the input file (in the format specified below), print to standard output the line segments discovered (in
the format specified below), and draw to standard draw the line segments discovered (in the format specified below). Here are the APIs.

public class Brute {
   public static void main(String[] args)
}

public class Fast {
   public static void main(String[] args)
}

Input format. Read the points from an input file in the following format: An integer N, followed by N pairs of integers (xy), each between 0 and 32,767. Below
are two examples.

% more input6.txt       % more input8.txt
6                       8
19000  10000             10000      0
18000  10000                 0  10000
32000  10000              3000   7000
21000  10000              7000   3000
 1234   5678             20000  21000
14000  10000              3000   4000
                         14000  15000
                          6000   7000

Output format. Print to standard output the line segments that your program discovers, one per line. Print each line segment as an ordered sequence of its constituent points, separated
by " -> ".

% java Brute input6.txt
(14000, 10000) -> (18000, 10000) -> (19000, 10000) -> (21000, 10000)
(14000, 10000) -> (18000, 10000) -> (19000, 10000) -> (32000, 10000)
(14000, 10000) -> (18000, 10000) -> (21000, 10000) -> (32000, 10000)
(14000, 10000) -> (19000, 10000) -> (21000, 10000) -> (32000, 10000)
(18000, 10000) -> (19000, 10000) -> (21000, 10000) -> (32000, 10000)

% java Brute input8.txt
(10000, 0) -> (7000, 3000) -> (3000, 7000) -> (0, 10000)
(3000, 4000) -> (6000, 7000) -> (14000, 15000) -> (20000, 21000) 

% java Fast input6.txt
(14000, 10000) -> (18000, 10000) -> (19000, 10000) -> (21000, 10000) -> (32000, 10000) 

% java Fast input8.txt
(10000, 0) -> (7000, 3000) -> (3000, 7000) -> (0, 10000)
(3000, 4000) -> (6000, 7000) -> (14000, 15000) -> (20000, 21000)

Also, draw the points using draw() and draw the line segments using drawTo().
Your programs should call draw() once for each point in the input file and it should call drawTo() once for each line segment
discovered. Before drawing, use StdDraw.setXscale(0, 32768) and StdDraw.setYscale(0, 32768) to rescale the coordinate system.

For full credit, do not print permutations of points on a line segment (e.g., if you output pqrs, do not also output either srqp or prqs).
Also, for full credit in Fast.java, do not print or plot subsegments of a line segment containing 5 or more points (e.g., if you output pqrst, do not also output either pqst or qrst);
you should print out such subsegments in Brute.java.

Deliverables. Submit only Brute.javaFast.java, and Point.java. We will supply stdlib.jar and algs4.jar. Your may not call any library functions other
than those in java.langjava.utilstdlib.jar, and algs4.jar.

This assignment was developed by Kevin Wayne.

Copyright ? 2005.

代码:

Point.java

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.java

public class Brute {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StdDraw.setXscale(0, 32768);
		StdDraw.setYscale(0, 32768);

		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);
			points[i].draw();
		}

		for (int i = 0; i < num; i++)
			for (int j = 0; j < num - 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 < num; i++)
			for (int j = i + 1; j < num; j++)
				for (int k = j + 1; k < num; k++)
					for (int l = k + 1; l < num; l++) {
						if (points[i].slopeTo(points[j]) == points[j].slopeTo(points[k])
								&& points[j].slopeTo(points[k]) == points[k].slopeTo(points[l])) {
							StdOut.print(points[i].toString() + "->" + points[j].toString() + "->"
									+ points[k].toString() + "->" + points[l].toString() + "\n");
							points[i].drawTo(points[l]);
						}
					}
	}

}

Fast.java(不是所有的测试案例都能通过)

import java.util.Arrays;

public class Fast {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StdDraw.setXscale(0, 32768);
		StdDraw.setYscale(0, 32768);

		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);
			points[i].draw();
		}

		for (int i = 0; i < num; i++)
			for (int j = 0; j < num - 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 < num;i++)
		// StdOut.print(points[i].toString()+"\n");

		for (int i = 0; i < num; i++) {
			Point temp[] = new Point[num];
			for (int j = 0; j < num; j++)
				temp[j] = points[j];
			Arrays.sort(temp, points[i].SLOPE_ORDER);
			// for(int j = 0;j < num;j++)
			// StdOut.print(temp[j].toString()+"\n");
			for (int j = 1; j < num - 2; j++)
			{
				if (temp[0].compareTo(temp[j]) == -1 && temp[j].compareTo(temp[j + 1]) == -1
						&& temp[j + 1].compareTo(temp[j + 2]) == -1)
				{
					int k = -1;
					if (temp[0].slopeTo(temp[j]) == temp[j].slopeTo(temp[j + 1])
							&& temp[j].slopeTo(temp[j + 1]) == temp[j + 1].slopeTo(temp[j + 2]))
					{
							k = j + 2;
							while (temp[k].compareTo(temp[k + 1]) == -1 && (k + 1) < num && temp[k - 1].slopeTo(temp[k]) == temp[k].slopeTo(temp[k + 1]))
								k++;
					}
					if(k != -1)
					{
						StdOut.print(temp[0].toString() + "->");
						temp[0].drawTo(temp[j]);
					}

					while(j < k)
					{
						StdOut.print(temp[j].toString() + "->");
						temp[j].drawTo(temp[j+1]);
						j++;
					}
					if(k != -1)
						StdOut.print(temp[k].toString());
					StdOut.print("\n");

				}
			}
		}
	}
}
时间: 2024-08-07 20:53:29

Algorithm Part I:Programming Assignment(3)的相关文章

Algorithm Part I:Programming Assignment(2)

问题描述: Programming Assignment 2: Randomized Queues and Deques Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to g

Programming Assignment 4: 8 Puzzle

The Problem. 求解8数码问题.用最少的移动次数能使8数码还原. Best-first search.使用A*算法来解决,我们定义一个Seach Node,它是当前搜索局面的一种状态,记录了从初始到达当前状态的移动次数和上一个状态.初始化时候,当前状态移动次数为0,上一个状态为null,将其放入优先级队列,通过不断的从优先级队列中取出Seach Node去扩展下一级的状态,直到找到目标状态.对于优先级队列中优先级的定义我们可以采用:Hamming priority function 和

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

自我总结: 1.编程的思维不够,虽然分析有哪些需要的函数,但是不能比较好的汇总整合 2.写代码能力,容易挫败感,经常有bug,很烦心,耐心不够好 题目: In this programming assignment you will implement one or more of the integer multiplication algorithms described in lecture. To get the most out of this assignment, your pro

C200 Programming Assignment

C200 Programming Assignment № 8Computer ScienceSchool of Informatics, Computing, and EngineeringMarch 30, 2019ContentsIntroduction 2Problem 1: Newton Raphson Root Finding Algorithm 4Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Programming Assignment 3 : Pattern Recognition

这周的这个问题是在给定一系列的点中寻找多点共线的模式. 计算机视觉重要的两个部分:特征检测(Feature Dectection)和模式识别(Pattern Recognition).特征检测提取出图片的重要特征,模式识别发掘出这些特征中的模式.这里探究的点共线的问题在现实生活中也有很多应用,比如统计数据分析. Problem. 从二维平面上的N个互不相同的点中,绘制出每个(最多)连接的4个或4个以上点集合的线段. Point data type. 给定的Point类型的API public c

Programming Assignment 1: WordNet

题目地址:http://coursera.cs.princeton.edu/algs4/assignments/wordnet.html 1. 题目阅读 WordNet定义 WordNet是指一个包含唯一根的有向无环图,图中每一组词表示同一集合,每一条边v→w表示w是v的上位词.和树不同的地方是,每一个子节点可以有许多父节点. 输入格式 同义词表 文件中每行包含一次同义名词.首先是序号:然后是词,用空格分开.若为词组,则使用下划线连接词组.最后是同义名词的注释 36,AND_circuit AN

CMPT 459.1-19. Programming Assignment

---title: "CMPT 459.1-19. Programming Assignment 1"subtitle: "FIFA 19Players"author: "Name - Student ID"output: html_notebook---### IntroductionThe data has detailed attributes for every player registered inthe latest edition

Programming Assignment 1: Z-Buffer Rendering

This project is to develop a simple Z-buffer renderer to view 3D models. This will be accomplished by importing a file for a 3D model derived of triangle polygons in a specified file format (below). Sample model files are provided but the progam will

第二周:神经网络的编程基础----------2、编程作业常见问题与答案(Programming Assignment FAQ)

Please note that when you are working on the programming exercise you will find comments that say "# GRADED FUNCTION: functionName". Do not edit that comment. The function in that code block will be graded. 1) What is a Jupyter notebook? A Jupyt