Coursera普林斯顿算法课第三次作业

2023-11-11 17:38

本文主要是介绍Coursera普林斯顿算法课第三次作业,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Point: 重点是Comparable和Comparator接口的区别和实现。另外需要特别注意点的坐标是整数类型而斜率是浮点数,所以在计算斜率时可以乘以1.0。其次要注意Java中正负零不相等的问题,即0/5与0/(-5)不相同。

import java.util.Comparator;
import edu.princeton.cs.algs4.StdDraw;public class Point implements Comparable<Point>{private int x;private int y;public Point(int x, int y){this.x = x;this.y = y;}// x and y are between 0 and 32767public void draw(){StdDraw.point(x, y);}// StdDraw with input between 0 and 1public void drawTo(Point that){StdDraw.line(x, y, that.x, that.y);}public String toString() {return "Point [x=" + x + ", y=" + y + "]";}// implementation for Comparablepublic 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;}	}public double slopeTo(Point that){if(this.compareTo(that) == 0){return Double.NEGATIVE_INFINITY;}else if(this.x == that.x){return Double.POSITIVE_INFINITY;}else if(this.y == that.y){return +0; // negative zero != positive zero}else{return (that.y - y) * 1.0 /(that.x - x); // integer to double}}public Comparator<Point> slopeOrder(){return new BySlope();}// implementation for Comparatorprivate class BySlope implements Comparator<Point>{public int compare(Point o1, Point o2) {if(slopeTo(o1) < slopeTo(o2)) return -1;if(slopeTo(o1) > slopeTo(o2)) return 1;return 0;}	}}

LineSegment:不做要求,测试时会提供。注意StdDraw的使用。

import edu.princeton.cs.algs4.StdDraw;public class LineSegment {private Point p_top;private Point p_bot;public LineSegment(Point p, Point q){p_top = p;p_bot = q;}public void draw(){p_top.drawTo(p_bot);}public String toString() {return "LineSegment [p1=" + p_top + ", p2=" + p_bot + "]";}public static void main(String[] args){Point p1 = new Point(15000,18000);Point p2 = new Point(8000,22000);Point p3 = new Point(600,9000);Point p4 = new Point(9000,5000);Point p5 = new Point(12000,10000);StdDraw.enableDoubleBuffering();StdDraw.setXscale(0, 32768);StdDraw.setYscale(0, 32768);StdDraw.setPenRadius(0.01);StdDraw.setPenColor(StdDraw.BLUE);p1.draw();p2.draw();p3.draw();p4.draw();p5.draw();StdDraw.show();StdDraw.setPenColor(StdDraw.MAGENTA);p1.drawTo(p5);p2.drawTo(p4);StdDraw.setPenColor(StdDraw.RED);p3.drawTo(p2);StdDraw.show();}
}

BruteCollinearPoints:使用了ArrayList及其自带的toArray方法。时间复杂度控制在N^4以内。注意不能直接对构造方法输入参数points进行排序,需要进行深度复制。

import java.util.ArrayList;
import edu.princeton.cs.algs4.Merge;public class BruteCollinearPoints {private Point[] pts;private ArrayList<LineSegment> lines;public BruteCollinearPoints(Point[] points){// deep copy to avoid mutating the constructor argumentcheckNullArgument(points);this.pts = new Point[points.length]; for(int k = 0; k < points.length; k++){pts[k] = points[k];}checkDuplicatedElement(pts); // mergesortlines = new ArrayList<LineSegment>(); // to avoid NullPointerExceptionfor(int k1 = 0; k1 < pts.length; k1++){for(int k2 = k1 + 1; k2 < pts.length; k2++){for(int k3 = k2 + 1; k3 < pts.length; k3++){if(pts[k1].slopeTo(pts[k2]) == pts[k1].slopeTo(pts[k3])){for(int k4 = k3 + 1; k4 < pts.length; k4++){if(pts[k1].slopeTo(pts[k2]) == pts[k1].slopeTo(pts[k4])){// k1, k2, k3, k4 are already sortedlines.add(new LineSegment(pts[k1], pts[k4]));}}}}}}}public int numberOfSegments(){return lines.size();}// line segment will contain at most 4 collinear pointspublic LineSegment[] segments(){return lines.toArray(new LineSegment[numberOfSegments()]);}private void checkDuplicatedElement(Point[] points){// sort input array by natural orderMerge.sort(points);// duplicated elementfor(int i=1; i<points.length; i++){if(points[i].slopeTo(points[i-1]) == Double.NEGATIVE_INFINITY){throw new IllegalArgumentException("Input contains repeated element!\n");}}}private void checkNullArgument(Point[] points){// null arrayif(points == null){throw new IllegalArgumentException("Input cannot be null!\n");}// null elementfor(int i = 0; i < points.length; i++){if(points[i] == null){throw new IllegalArgumentException("Input contains null element!\n");}	}}}

FastCollinearPoints:难点在于如何确认找到的segment是不是之前找到过的线段的subsegment,同时要保证时间复杂度在N*N*lg(N)以内。以下代码通过使用复杂度为lg(N)的BinarySearch成功地完成了任务。

import java.util.ArrayList;
import java.util.Arrays;import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Merge;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;public class FastCollinearPoints {private Point[] pts;private ArrayList<LineSegment> lines;/*** constructor ~ n*nlg(n)* @param points*/public FastCollinearPoints(Point[] points){checkNullArgument(points);this.pts = new Point[points.length]; for(int k = 0; k < points.length; k++){pts[k] = points[k];}checkDuplicatedElement(pts); // mergesort ~ nlg(n)lines = new ArrayList<LineSegment>(); // to avoid NullPointerException// IndexOutOfBoundsException for i < pts.lengthfor(int i = 0; i < pts.length - 1; i++){Double[] slopesB4 = new Double[i]; // slopes with points upstreamPoint[] pointsAf = new Point[pts.length - i - 1]; // points downstreamfor(int k = 0; k < i; k++) {slopesB4[k] = pts[i].slopeTo(pts[k]);}for(int j = 0; j < pts.length - i - 1; j++) { pointsAf[j] = pts[j + i + 1]; }// sort upstream slopes by natural order ~ nlg(n)Merge.sort(slopesB4); // sort downstream points by slope order to pts[i] ~ nlg(n)Arrays.sort(pointsAf, pts[i].slopeOrder()); addSegment(slopesB4, pts[i], pointsAf); // ~ nlg(n)}}/*** add appropriate line segment ~ nlg(n)* @param slopesB4: slopes of upstream points to point p* @param p: the origin point* @param pointsAf: downstream points*/private void addSegment(Double[] slopesB4, Point p, Point[] pointsAf){int count = 1;double lastSlope = p.slopeTo(pointsAf[0]);for(int i = 1; i < pointsAf.length; i++){double slope = p.slopeTo(pointsAf[i]);if(slope != lastSlope){if(count >= 3 && !subSegment(lastSlope, slopesB4)){lines.add(new LineSegment(p, pointsAf[i - 1]));}		count = 1;}else{count++; // the loop terminates with the last possible segment unchecked}lastSlope = slope;}// check the last pointif(count >= 3 && !subSegment(lastSlope, slopesB4)){lines.add(new LineSegment(p, pointsAf[pointsAf.length - 1]));}}/*** binary search the given slope in slopsB4 ~ lg(n)* @param s: the given slope* @param slopes: of upstream points to the origin point* @return */private boolean subSegment(double s, Double[] slopes){int lo = 0;int hi = slopes.length - 1;while(lo <= hi){int mid = lo + (hi - lo) / 2;if(s < slopes[mid]) hi = mid - 1;else if(s > slopes[mid]) lo = mid + 1;	else return true;}return false;}public int numberOfSegments(){return lines.size();}public LineSegment[] segments(){return lines.toArray(new LineSegment[numberOfSegments()]);}private void checkDuplicatedElement(Point[] points){// sort input array by natural orderMerge.sort(points);// duplicated elementfor(int i=1; i<points.length; i++){if(points[i].slopeTo(points[i-1]) == Double.NEGATIVE_INFINITY){throw new IllegalArgumentException("Input contains repeated element!\n");}}}private void checkNullArgument(Point[] points){// null arrayif(points == null){throw new IllegalArgumentException("Input cannot be null!\n");}// null elementfor(int i = 0; i < points.length; i++){if(points[i] == null){throw new IllegalArgumentException("Input contains null element!\n");}	}}public static void main(String[] args){// read n points from a fileIn in = new In(args[0]);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);}// draw pointsStdDraw.enableDoubleBuffering();StdDraw.setXscale(0, 32768);StdDraw.setYscale(0, 32768);for(Point p : points){p.draw();}StdDraw.show();FastCollinearPoints collinear = new FastCollinearPoints(points);for(LineSegment sg : collinear.segments()){StdOut.println(sg);sg.draw();}StdDraw.show();}}

这篇关于Coursera普林斯顿算法课第三次作业的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系

作业提交过程之HDFSMapReduce

作业提交全过程详解 (1)作业提交 第1步:Client调用job.waitForCompletion方法,向整个集群提交MapReduce作业。 第2步:Client向RM申请一个作业id。 第3步:RM给Client返回该job资源的提交路径和作业id。 第4步:Client提交jar包、切片信息和配置文件到指定的资源提交路径。 第5步:Client提交完资源后,向RM申请运行MrAp

康拓展开(hash算法中会用到)

康拓展开是一个全排列到一个自然数的双射(也就是某个全排列与某个自然数一一对应) 公式: X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[1]*0! 其中,a[i]为整数,并且0<=a[i]<i,1<=i<=n。(a[i]在不同应用中的含义不同); 典型应用: 计算当前排列在所有由小到大全排列中的顺序,也就是说求当前排列是第

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖

【数据结构】——原来排序算法搞懂这些就行,轻松拿捏

前言:快速排序的实现最重要的是找基准值,下面让我们来了解如何实现找基准值 基准值的注释:在快排的过程中,每一次我们要取一个元素作为枢纽值,以这个数字来将序列划分为两部分。 在此我们采用三数取中法,也就是取左端、中间、右端三个数,然后进行排序,将中间数作为枢纽值。 快速排序实现主框架: //快速排序 void QuickSort(int* arr, int left, int rig

poj 3974 and hdu 3068 最长回文串的O(n)解法(Manacher算法)

求一段字符串中的最长回文串。 因为数据量比较大,用原来的O(n^2)会爆。 小白上的O(n^2)解法代码:TLE啦~ #include<stdio.h>#include<string.h>const int Maxn = 1000000;char s[Maxn];int main(){char e[] = {"END"};while(scanf("%s", s) != EO

秋招最新大模型算法面试,熬夜都要肝完它

💥大家在面试大模型LLM这个板块的时候,不知道面试完会不会复盘、总结,做笔记的习惯,这份大模型算法岗面试八股笔记也帮助不少人拿到过offer ✨对于面试大模型算法工程师会有一定的帮助,都附有完整答案,熬夜也要看完,祝大家一臂之力 这份《大模型算法工程师面试题》已经上传CSDN,还有完整版的大模型 AI 学习资料,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

dp算法练习题【8】

不同二叉搜索树 96. 不同的二叉搜索树 给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。 示例 1: 输入:n = 3输出:5 示例 2: 输入:n = 1输出:1 class Solution {public int numTrees(int n) {int[] dp = new int

Codeforces Round #240 (Div. 2) E分治算法探究1

Codeforces Round #240 (Div. 2) E  http://codeforces.com/contest/415/problem/E 2^n个数,每次操作将其分成2^q份,对于每一份内部的数进行翻转(逆序),每次操作完后输出操作后新序列的逆序对数。 图一:  划分子问题。 图二: 分而治之,=>  合并 。 图三: 回溯: