普林斯顿大学算法Week3:CollinearPoints共线模式识别(99分)--总结及代码

本文主要是介绍普林斯顿大学算法Week3:CollinearPoints共线模式识别(99分)--总结及代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

总结

(代码有详细注释)
  1. 本课讲了归并排序,作业应用是排序进行共线的模式识别,java1.8中的排序用的是tim排序,结合了归并排序与插入排序,属于稳定排序:排序之后相同元素的相对位置会不会改变
  2. Point.java中有个非常重要的方法,compareTo(),它定义:纵坐标越小则点越小,如果纵坐标相同,那么横坐标越小则点越小.(如果作业中要求横坐标也是按顺序排列,那么排序后的点集映射到二维坐标系中是非递减的折线, 这样找共线只用一层循环即可,可惜作业没加上对x的限制)
  3. 比较大小,一开始我用的是points[i-1] == point[i],尽管坐标相同但是points[i-1]不等于points[i]
    因为points[i-1]和points[i]表示引用,在堆中指向两个不同的地址,比较大小得用points[i-1].compareTo(points[i])
  4. 在FastCollinearPoints.java中,一定要注意什么时候对共线点数变量count进行判断,有两种情况,一个是,相邻元素与参考点的斜率不同;另一个是循环到最后一个元素.这两种情况在代码注释中有解释
  5. 唯一一处FAILED,扣了1分,没系统学过java,先跳过了
Test 7: check for dependence on either compareTo() or compare()returning { -1, +1, 0 } instead of { negative integer,positive integer, zero }* filename = equidistant.txt- number of entries in student   solution: 0- number of entries in reference solution: 4- 4 missing entries in student solution, including: '(30000, 0) -> (20000, 10000) -> (10000, 20000) -> (0, 30000)'
==> FAILED
  1. week3课件中,递归调用的图示:
    这是包含两个递归调用的递归 (图示只画了一半)
    Merge.jpg

代码

(如需提交,请删除中文注释)

一:Point.java

import java.util.Comparator;
import edu.princeton.cs.algs4.StdDraw;
public class Point implements Comparable<Point> {// x-coordinate of this pointprivate final int x;// y-coordinate of this pointprivate final int y;// constructs the point (x, y)public Point(int x, int y) {this.x = x;this.y = y;} // draws this pointpublic   void draw() {StdDraw.point(x,y);}// draws the line segment from this point to that pointpublic   void drawTo(Point that) {StdDraw.line(this.x, this.y, that.x, that.y);}// string representationpublic String toString() {return "(" + x + ", " + y + ")";}// compare two points by y-coordinates, breaking ties by x-coordinates  public  int compareTo(Point that) {if(y<that.y || (y==that.y && x<that.x)) return -1;else if(y==that.y && x==that.x) return 0;else return +1;}   // the slope between this point and that pointpublic  double slopeTo(Point that) {if(x==that.x && y==that.y) return Double.NEGATIVE_INFINITY;if(x==that.x && y!=that.y) return Double.POSITIVE_INFINITY;     if(y==that.y) return +0.0;return (double)(y-that.y)/(x-that.x);}// compare two points by slopes they make with this pointpublic Comparator<Point> slopeOrder(){return new SlopeOrder();}//nested class//sort ruleprivate class SlopeOrder implements Comparator<Point>{public int compare(Point p,Point q) {//p点斜率大if(slopeTo(p)<slopeTo(q)) return -1;//p点斜率小else if(slopeTo(p)>slopeTo(q)) return 1;//p,q斜率相等else return 0;}}public static void main(String[] args) {Point p1 = new Point(0,0);Point p2 = new Point(1,1);Point p3 = new Point(2,2);Point p4 = new Point(2,1);Point p5 = new Point(4,1);System.out.println("p1.compareTo(p1) is "+p1.compareTo(p2));System.out.println("p2.compareTo(p1) is "+p2.compareTo(p1));System.out.println("p1.compareTo(p1) is "+p1.compareTo(p1)+"\n");System.out.println("p1.slopeTo(p2) is " +p1.slopeTo(p2));System.out.println("p1.slopeTo(p4) is "+p1.slopeTo(p4));System.out.println("p1.slopeTo(p1) is "+p1.slopeTo(p1));System.out.println("p3.slopeTo(p4) is "+p3.slopeTo(p4));System.out.println("p2.slopeTo(p5) is "+p2.slopeTo(p5));}
}

二:BruteCollinearPoints.java

import java.util.ArrayList;
import java.util.Arrays;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Insertion;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdDraw;public class BruteCollinearPoints {//to store line segmentsprivate ArrayList<LineSegment> LineSegmentList;//to store the given pointsprivate Point[] points;//在构造函数中找出由4点构成的线段(作业说了:没有5点及更多点共线的情况)// finds all line segments containing 4 pointpublic BruteCollinearPoints(Point[] pointsIn) { //三种异常//一:if the argument to the constructor is nullSystem.out.println(" a ");if(pointsIn == null) throw new IllegalArgumentException("there is no point");//二:if any point in the array is nullint N = pointsIn.length;for(int i=0;i<N;i++) if(pointsIn[i]==null) throw new IllegalArgumentException("exist null point");//三:if the argument to the constructor contains a repeated point//检查是否有重复的点,先排序,再查重会方便,作业允许这样: For example, you may use Arrays.sort()points = new Point[N];for(int i=0;i<N;i++) points[i] = pointsIn[i];Arrays.sort(points);for(int i=1;i<N;i++) if(points[i-1].compareTo(points[i])==0) throw new IllegalArgumentException("exist repeated point"); //to save every required line segmentLineSegmentList = new ArrayList<LineSegment>();//find line segmentfor(int dot1=0;dot1<=N-4;dot1++) {for(int dot2=dot1+1;dot2<=N-3;dot2++) {//k12:the slope between point[dot2] and point[dot1]double k12 = points[dot2].slopeTo(points[dot1]);for(int dot3=dot2+1;dot3<=N-2;dot3++) {//k13:the slope between point[dot3] and point[dot1]double k13 = points[dot3].slopeTo(points[dot1]);if(k13 != k12) continue;for(int dot4=dot3+1;dot4<=N-1;dot4++) {//k14:the slope between point[dot4] and point[dot1]double k14 = points[dot4].slopeTo(points[dot1]);if(k14 != k12) continue;//find a line segmentLineSegment linesegment = new LineSegment(points[dot1],points[dot4]);LineSegmentList.add(linesegment);}}}}}// the number of line segmentspublic int numberOfSegments() {return LineSegmentList.size();}// the line segmentspublic LineSegment[] segments() {LineSegment[] segments = new LineSegment[LineSegmentList.size()];int index=0;for(LineSegment Line : LineSegmentList) {segments[index++] = Line;}return segments;}    //mainpublic static void main(String[] args) {In in = new In("src/week3/input8.txt"); int n = in.readInt();StdOut.println("total "+n+" points");Point[] points = new Point[n];for (int i = 0; i < n; i++) {int x = in.readInt();int y = in.readInt();StdOut.println("("+x+","+y+")"); points[i] = new Point(x,y);}       //draw the pointsStdDraw.enableDoubleBuffering();StdDraw.setXscale(0, 32768);StdDraw.setYscale(0, 32768);StdDraw.setPenColor(StdDraw.RED);StdDraw.setPenRadius(0.01);for (Point p : points) {p.draw();}StdDraw.show();              // print and draw the line segmentsBruteCollinearPoints collinear = new BruteCollinearPoints(points);StdOut.println(collinear.numberOfSegments());for (LineSegment segment : collinear.segments()) {StdOut.println(segment);segment.draw();}StdDraw.show();          }
}

三:FastCollinearPoints.java

import java.util.ArrayList;
import java.util.Arrays;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;//much faster than the brute-force solution
public class FastCollinearPoints {//to store line segmentsprivate ArrayList<LineSegment> LineSegmentList;//to store the given pointsprivate Point[] points;// finds all line segments containing 4 or more pointspublic FastCollinearPoints(Point[] pointsIn) {//三种异常//一:if the argument to the constructor is nullif(pointsIn == null) throw new IllegalArgumentException("there is no point");//number of pointsint N=pointsIn.length;//二:if any point in the array is nullfor(int i=0;i<N;i++) if(pointsIn[i]==null) throw new IllegalArgumentException("exist null point");//三:if the argument to the constructor contains a repeated point//检查是否有重复的点,先排序,再查重会方便,作业允许这样: For example, you may use        Arrays.sort()//同时有利于后面排除重复线段points = new Point[N];for(int i=0;i<N;i++) points[i] = pointsIn[i];//用的是结合了归并和插入的tim排序,稳定排序Arrays.sort(points);for(int i=1;i<N;i++) if(points[i-1].compareTo(points[i])==0) throw new IllegalArgumentException("exist repeated point");//to save every required line segmentLineSegmentList = new ArrayList<LineSegment>();//当前的参考点Point currentCheck;//对照点重新存储,不包括参考点,共N-1个Point[] otherPoints = new Point[N-1];//开始比较斜率,一个一个来for (int i=0;i<N;i++) {currentCheck = points[i];// copy points without Point currentCheck to otherPointsfor(int j=0;j<N;j++) {if(j<i) otherPoints[j] = points[j];if(j>i) otherPoints[j-1] = points[j];}//根据斜率对点排序//用的是结合了归并和插入的tim排序,稳定排序Arrays.sort(otherPoints,currentCheck.slopeOrder());//遍历已经排序的otherPoints找线段//注意,归并和插入排序都是稳定的,所以tim排序是稳定的,这非常重要//配合Point的compareTo方法,可以直接过滤掉重复线段//一开始没太注意compareTo方法,后来发现这个方法能固定住点之间的相对位置,所以可以过滤重复线段//两点共线int count=2;for(int k=1;k<N-1;k++) {double k1 = otherPoints[k-1].slopeTo(currentCheck);double k2 = otherPoints[k].slopeTo(currentCheck);if(k1==k2) {count++;//当循环到最后一个点,同时这个点和前面的点共线if(k==N-2) {//如果4点及以上共线,并且otherPoints中与参考点共线且排在最左边的点比参考点大的话,注意此处是遍历到头,所以索引是k-count+2if(count>=4 && currentCheck.compareTo(otherPoints[k-count+2])==-1) { //线段起点Point start = currentCheck;//线段终点Point end = otherPoints[k];LineSegment linesegment = new LineSegment(start,end);LineSegmentList.add(linesegment);}}}else{//如果4点及以上共线,并且otherPoints中与参考点共线且排在最左边的点比参考点大的话,索引是k-count+1if(count>=4 && currentCheck.compareTo(otherPoints[k-count+1])==-1) {Point start = currentCheck;Point end = otherPoints[k-1];LineSegment linesegment = new LineSegment(start,end);LineSegmentList.add(linesegment);}count=2;}}}}// the number of line segmentspublic  int numberOfSegments() {return LineSegmentList.size();}// the line segmentspublic LineSegment[] segments() {LineSegment[] segments = new LineSegment[LineSegmentList.size()];int index=0;for(LineSegment Line : LineSegmentList) {segments[index++] = Line;}return segments;}//mainpublic static void main(String[] args) {In in = new In("src/week3/input9.txt"); int n = in.readInt();StdOut.println("total "+n+" points");Point[] points = new Point[n];for (int i = 0; i < n; i++) {int x = in.readInt();int y = in.readInt();StdOut.println("("+x+","+y+")"); points[i] = new Point(x,y);}//draw the pointsStdDraw.enableDoubleBuffering();StdDraw.setXscale(0, 32768);StdDraw.setYscale(0, 32768);StdDraw.setPenColor(StdDraw.RED);StdDraw.setPenRadius(0.01);for (Point p : points) {p.draw();}StdDraw.show();//print and draw the line segmentsFastCollinearPoints collinear = new FastCollinearPoints(points);StdOut.println(collinear.numberOfSegments());for (LineSegment segment : collinear.segments()) {StdOut.println(segment);segment.draw();}StdDraw.show();          }
}

WelcomeToMyBlog

这篇关于普林斯顿大学算法Week3:CollinearPoints共线模式识别(99分)--总结及代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/219997

相关文章

javaScript在表单提交时获取表单数据的示例代码

《javaScript在表单提交时获取表单数据的示例代码》本文介绍了五种在JavaScript中获取表单数据的方法:使用FormData对象、手动提取表单数据、使用querySelector获取单个字... 方法 1:使用 FormData 对象FormData 是一个方便的内置对象,用于获取表单中的键值

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl

Rust格式化输出方式总结

《Rust格式化输出方式总结》Rust提供了强大的格式化输出功能,通过std::fmt模块和相关的宏来实现,主要的输出宏包括println!和format!,它们支持多种格式化占位符,如{}、{:?}... 目录Rust格式化输出方式基本的格式化输出格式化占位符Format 特性总结Rust格式化输出方式

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(

MySQL数据库函数之JSON_EXTRACT示例代码

《MySQL数据库函数之JSON_EXTRACT示例代码》:本文主要介绍MySQL数据库函数之JSON_EXTRACT的相关资料,JSON_EXTRACT()函数用于从JSON文档中提取值,支持对... 目录前言基本语法路径表达式示例示例 1: 提取简单值示例 2: 提取嵌套值示例 3: 提取数组中的值注意