Algorithm Part I: programming assignment (3)

Source: Internet
Author: User
Tags comparable

Problem description:

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 DetectionAndPattern Recognition. Feature Detection involves selecting important features of the image; pattern recognition involves discovering patterns in the features. we will investigate a participant ly clean pattern recognition problem involving points and line segments. this kind of pattern recognition arises in your other applications such as statistical data analysis.

The problem.Given a setNDistinct 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 typePointThat 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 Draw (), Drawto (), And Tostring ()Methods. Your job is to add the following components.

  • TheCompareto ()Method shoshould compare points by theirY-Coordinates, breaking ties by theirX-Coordinates. formally, the invoking point (X0,Y0) isLessThe argument point (X1,Y1) if and only if eitherY0 <Y1 Or ifY0 =Y1 andX0 <X1.

  • TheSlopeto ()Method shocould return the slope between the invoking point (X0,Y0) and the argument point (X1,Y1), 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.

  • TheSlope_orderComparator shoshould compare points by the slopes they make with the invoking point (X0,Y0). formally, the point (X1,Y1) isLessThe point (X2,Y2) 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 inSlopeto ()Method.

Brute force.Write a programBrute. JavaThat 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 pointsP,Q,R, AndSAre collinear, check whether the slopesPAndQ,PAndR, AndPAndSAre all equal.

The order of growth of the running time of your program shocould beN4 In the worst case and it shoshould use space proportionalN.

A faster, sorting-based solution.Remarkably, it is possible to solve the problem much faster than the brute-force solution described abve. Given a pointP, The following method determines whetherPParticipant in a set of 4 or more collinear points.

  • ThinkPAs the origin.

  • For each other pointQ, Determine the slope it makesP.

  • Sort the points according to the slopes they makesP.

  • Check if any 3 (or more) adjacent points in the sorted order have equal slopes with respectP. If so, these points, togetherP, 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 programFast. JavaThat implements this algorithm. The order of growth of the running time of your program shocould beN2 logNIn the worst case and it shoshould use space proportionalN.

APIS.Each program shocould 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 integerN, FollowedNPairs of Integers (X,Y), Each between 0 and 32,767. Below are two examples.

% more input6.txt       % more input8.txt6                       819000  10000             10000      018000  10000                 0  1000032000  10000              3000   700021000  10000              7000   3000 1234   5678             20000  2100014000  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 asOrderedSequence of its constituent points, separated"->".

% 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 shocould call Draw ()Once for each point in the input file and it shoshould 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 printPermutationsOf points on a line segment (e.g., if you outputPQRS, Do not also output eitherSRQPOrPRQS). Also, for full credit inFast. Java, Do not print or plotSubsegmentsOf a line segment containing 5 or more points (e.g., if you outputPQRST, Do not also output eitherPQSTOrQRST); You shoshould print out such subsegments inBrute. Java.

Deliverables.Submit onlyBrute. Java,Fast. Java, AndPoint. Java. We will supplyStdlib. JarAndAlgs4.jar. Your may not call any library functions other than those inJava. Lang,Java. util,Stdlib. Jar, AndAlgs4.jar.

This assignment was developed by Kevin Wayne.
Copyright? 2005.

Code:

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 coordinateprivate final int y; // y coordinatepublic 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;elsereturn (that.y - this.y) * 1.0 / (that.x - this.x);}private class PointCmp implements Comparator<Point> {@Overridepublic int compare(Point o1, Point o2) {// TODO Auto-generated method stubif (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;elsereturn 0;}}@Overridepublic int compareTo(Point that) {// TODO Auto-generated method stubif (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;elsereturn 1;}public String toString() {/* DO NOT MODIFY */return "(" + x + ", " + y + ")";}public static void main(String[] args) {// TODO Auto-generated method stubIn 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 stubStdDraw.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 (not all test cases can pass)

import java.util.Arrays;public class Fast {public static void main(String[] args) {// TODO Auto-generated method stubStdDraw.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");}}}}}


Algorithm Part I: programming assignment (3)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.