COMPX123 HashMap Algorithm Description

news/2024/9/21 17:20:35/文章来源:https://www.cnblogs.com/WX-codinghelp/p/18424263

COMPX123  Assignment 3

S2 2024

This assignment is due on September 22 and should be submitted on Grade- scope. All submitted work must be done individually without consulting someone else’s solutions in accordance with the University’s “Academic Dishonesty and Plagiarism” policies.

Before you read any further, go to the last page of this document and read the Written Assignment Guidelines section.

Problem 1. (10 points) In this question we’re going to analyse a response gener- ated by an AI, in this case ChatGPT. It was asked to design an algorithm for the following problem that runs in O(n2 log n) (expected) time, argue its correctness, and analyse its running time.

Problem Description: You and your best friend just got out of the movies and are very hungry; unfortunately, it is now very late at night and all restaurants are closed.  You manage to find, by chance, some vending machine still full of very...  nutritious foods (bags of chips, and the occasional cereal bar).  Looking into your pockets, you look what change you have, in order to try and buy something (anything!) to eat.

You have n coins of various values. So does your friend! As for the vending machine...  it contains n different "food items" each with its own price.  Looks like you may eat tonight... except for two things:

• the vending machine is old and somewhat broken: it only accepts at most two coins, and does not return change:  you must put  exactly the right price to get the item you ask for.

• out of fairness, you and your friend refuse to pay for the whole thing alone. So each of you has to contribute (no matter how little):  to buy the food, each of you has to contribute at least one coin.

Which means that, if you want to eat tonight, you must figure out if there is an item in the vending machine whose price is exactly equal to the sum of two coins, one from you and one from your friend. And you are very hungry, so you want to figure that out fast.

Your task:  given three arrays Y, F, and V (You, Friend, Vending machine) each containing n positive integers, decide if there exist 0 ≤ i, j, k < n such that Y[i] + F[j] = V[k]. You can assume that all integers in all arrays are distinct (also between different arrays). Since you want to eat soon, you want an algorithm for this task which solves your problem fast: running in (expected) time O(n2 log n).

Example:

Y = [3, 2, 1], F = [4, 5, 6], V = [50, 8, 13].

We need to return true, since Y[1] + F[2] = V[1] (i.e., 2 + 6 + 8).

For the same Y and F, but with V =  [50, 2123, 9123], we’d return false, as there are no i, j, and k such that Y[i] + F[j] = V[k].

AI Output:

Algorithm Description:

1. Hash Map Initialization: Start by creating a hash map (‘map_v‘) that maps each price in array ‘V‘ to its index. This  allows us to quickly lookup whether a specific price exists in ‘V‘ .

2. Iterate Over Pairs:

• Use two nested loops to iterate over all pairs ‘(i, j)‘ where ‘i‘ is an index in array ‘Y‘ and ‘j‘ is an index in array ‘F‘ .

• For each pair ‘(i, j)‘, calculate the sum ‘sum = Y[i] + F[j]‘ .

3. Binary Search for Matching Price:

• For each calculated sum ‘sum‘,check if ‘sum‘ exists in ‘map_v‘ .

• If ‘sum‘ exists, retrieve its index from ‘map_v‘ .

4. Check Validity: Ensure that the retrieved index from ‘map_v‘ is different from ‘i‘ and ‘j‘ to satisfy the condition that you and your friend are both contributing at least one coin.

5. Return Result:

• If a valid index ‘k‘ is found that satisfies the conditions, return ‘true‘ .

• If no such triplet ‘(i, j, k)‘ is found after checking all pairs, return ‘false‘ .

Correctness Proof:

• Hash Map Usage: By using a hash map for ‘V‘, we achieve O(1) average- time complexity for lookups, ensuring efficiency in checking whether a sum exists.

• Binary Search: The binary search operation (using ‘lower_bound‘ or sim- ilar) for finding the index in ‘V‘ ensures that each lookup operation is efficient within the nested loop structure.

Time Complexity Analysis:

• Hash Map Construction: Building ‘map_v‘ takes O(n) time.

• Nested Loops: There are O(n2 ) pairs ‘(i, j)‘ to consider.

• Binary Search:  Each binary search operation within the nested loop is O(log n).

Therefore, the overall time complexity is O(n2 log n), dominated by the nested loops and the binary search operations.

Your task: To analyse the above response consider each of the following ques- tions and briefly explain your answer to each.

 

a) Does the AI response answer the question, i.e., does the algorithm solve the stated problem and does it run in the required time?

b) Is the algorithm described insufficient detail,i.e., is all information present or are any parts unclear or missing?

c) Is the correctness argument complete or are there leaps or errors in the logic?

d) Is the running time analysis correct for the provided algorithm?

Problem 2. (25 points)

The company Versatile Routing Over Outstanding Metal or VROOM produces routers and prides itself in the fact that at no point during the lifetime of any of its routers the average delay is larger than a certain value X.   As  one of their Quality Control Engineers, you’re tasked with testing a new range of their routers to ensure these too satisfy this requirement. We’re testing k > 0 routers, each identified using a distinct integer. Because we’re using the ultimate black box testing techniques, we don’t know beforehand what these integers are and k isn’t known either (and k is not a constant).  Whenever a router exceeds the maximum allowed average delay X, it’s removed from the testing suite and sent to R&D for analysis, never to be seen again. You’re tasked with designing a data structure that supports the testing process, including the following operations:

• initialize(): creates the (empty) data structure in O(1) time.

• add-data(ID, delay): updates the average delay of router ID using a new data point delay in O(log k) time.

•  current-delay(ID):  returns the current average delay of router  ID in O(log k) time, if it’s part of the test suite, and returns null otherwise.

• max-delay(): returns the ID of the router with the current highest average delay in O(1) time, or null if no routers remain in the test suite.

You can assume that the delay is always a non-negative integer.  You should ensure that after every operation only routers with an average delay of at most X are stored in the data structure (routers with average delay more than X are sent to R&D).  Your data structure should take O(k) space, regardless of how much data is added for any specific router. Remember to

a) Design a data structure that supports the required operations in the re- quired time and space.

b) Briefly argue the correctness of your data structure and operations.

c) Analyse the running time of your operations and space of your data structure.

 

 

Problem 3. (25 points)

We’re volunteering in the Bushfire Prevention Club and we’re tasked with de- signing an algorithm to predict the spread of bushfires. Our input is given as a simple undirected graph G = (V, E) (|V| = n vertices and |E| = m edges) in ad- jacency list representation and an array of vertices F ⊆ V that are on fire. We’re told that a vertex v ̸∈ F catches fire if at least 3 of its neighbours are already on fire. Your task is to compute all vertices of V that are on fire if fires are started at all vertices in F (and we make no attempt to prevent the fire from spreading).

Example:

 

If F = {b, c, g} then we need to report {a, b, c, d, g}:  {b, c, g} are initially on fire and together set d on fire, and in turn {b, c, d} set a on fire as well.  Note that e and f  don’t catch fire, since fewer than 3 of their neighbours are on fire.  If F = {d, e, f}, we report {d, e, f , g} since {d, e, f} make g catch fire and no other vertex has 3 burning neighbours after that.

 

Design an algorithm that given an initial set of burning vertices F, computes all burning vertices of V. For full marks, your algorithm should run in O(n + m) time. Remember to:

a) describe your algorithm in plain English,

b) argue its correctness, and

c) analyze its time complexity.

Written Assignment Guidelines

• Assignments should be typed and submitted as pdf (no pdf containing text as images, no handwriting).

• Start by typing your student ID at the top of the first page of your submis- sion. Do not type your name.

• Submit only your answers to the questions. Do not copy the questions.

• When asked to give a plain English description, describe your algorithm as you would to a friend over the phone, such that you completely and unambiguously describe your algorithm, including all the important (i.e., non-trivial) details.  It often helps to give a very short (1-2 sentence) de- scription of the overall idea, then to describe each step in detail. At the end you can also include pseudocode, but this is optional.

• In particular, when designing an algorithm or data structure, it might help you (and us) if you briefly describe your general idea, and after that you might want to develop and elaborate on details.  If we don’t see/under- stand your general idea, we cannot give you marks for it.

• Be careful with giving multiple or alternative answers. If you give multiple answers, then we will give you marks only for "your worst answer", as this indicateshow well you understood the question.

• Some of the questions are very easy (with the help of the slides or book). You can use the material presented in the lecture or book without proving it. You do not need to write more than necessary (see comment above).

• When giving answers to questions, always prove/explain/motivate your answers.

• When giving an algorithm as an answer, the algorithm does not have to be given as (pseudo-)code.

• If you do give (pseudo-)code, then you still have to explain your code and your ideas in plain English.

• Unless otherwise stated, we always ask about worst-case analysis, worst- case running times, etc.

• As done in the lecture, and as it is typical for an algorithms course, we are interested in the most efficient algorithms and data structures, though slower solutions may receive partial marks.

• If you use further resources (books, scientific papers, the internet,...)  to formulate your answers, then add references to your sources and explain it in your own words. Only citing a source doesn’t show your understanding and will thus get you very few (if any) marks.  Copying from any source without reference is considered plagiarism.

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/801103.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

了解如何在 lt;lines (Modulojs) 中创建 API 支持的 Zelda BOTW 怪物画廊 Web 组件

模数教程回来了!大家好!暑假结束后,我带着 modulo 教程回来了。我正在制作更多教程 - 请继续关注。也就是说,如果您对我的下一个主题有任何特别的想法,请务必在评论中告诉我!我的上一篇教程是关于 api 驱动的 pokmon dance party 组件的超级快速且有趣的“仅 html,无 js…

Cortex-A7 MPCore 架构

Cortex-A7 MPCore 架构 1)Cortex-A7 MPCore 简介 Cortex-A7 MPcore 处理器支持 1~4 核,通常是和 Cortex-A15 组成 big.LITTLE 架构的,Cortex-A15 作为大核负责高性能运算,比如玩游戏啥的, Cortex-A7 负责普通应用,因为 CortexA7 省电。 Cortex-A7 本身性能也不弱,不要…

Zlmedia搭建简记

进入新公司之后,发现他们的视频播放使用的是ZlmediaKit这个工具,自己尝试使用了一下发现很好用,于是在自己机器上搭建了一个服务玩玩。 因为没有在线的摄像头,所以这里采用的是ffmpeg推送mp4文件作为视频流输入,推送到zlmedia服务,再利用zlmedia本身所带的拉流服务,最终…

C 风格字符串函数

▲《C++ Primer》 P109 我们无法保证 c_str 函数返回的数组一直有效,事实上,如果后续的操作改变了 string 的值就可能让之前返回的数组失去效用。 WARNING: 如果执行完 c_str() 函数后程序想一直都能使用其返回的数组,最好将该数组重新拷贝一份。

基于IDF的ESP32S3-LVGL DEMO移植

简介 ESP32-32出色的性价比,较好的性能与内存空间,可以好利用来完成GUI显示库的加载 LVGL LVGL是一款比较流行的致力于MCU与MPU创建漂亮UI的嵌入式图形库,免费且开源。 硬件 硬件采用的是正点原子的ESP32-S3 屏幕使用的是SPI通信方式,配合IO口控制(RST,A0),来实现LCD屏幕…

nginx: 按ip地址限流

一,以固定的速度提供服务 语法: 例子 limit_req_zone $binary_remote_addr zone=test:10m rate=2r/s;server { location / { limit_req zone=test; }} 语法: imit_req_zone 用于设置限流和共享内存区域的参数,格式为: limit_req_zone key zone rate。 key: 定…

Free5GC源码研究(2) - 单个NF的软件架构

前文我们总览了free5gc的总体软件架构。整一个free5gc系统又由几个NF(Network Function)组成,所以本文继续深入研究单个NF的软件架构。要研究NF的软件架构,最直接的方式是找一个简单的NF来回观摩。free5gc/ausf算是比较简单的一个,然而我发现了一个更简单的NF,叫做andy89…

一,初始 MyBatis-Plus

一,初始 MyBatis-Plus @目录一,初始 MyBatis-Plus1. MyBatis-Plus 的概述2. 入门配置第一个 MyBatis-Plus 案例3. 补充说明:3.1 通用 Mapper 接口介绍3.1.1 Mapper 接口的 “增删改查”3.1.1.1 查询所有记录3.1.1.2 插入一条数据3.1.1.3 删除一条数据3.1.1.4 更新一条数据3.…

[神经网络与深度学习笔记]LDA降维

LDA降维 LinearDiscriminant Analysis 线性判别分析,是一种有监督的线性降维算法。与PCA保持数据信息不同,LDA的目标是将原始数据投影到低维空间,尽量使同一类的数据聚集,不同类的数据尽可能分散 步骤:计算类内散度矩阵\(S_b\) 计算类间散度矩阵\(S_w\) 计算矩阵\(S_w^{-1…

C++ 指针和迭代器支持的操作

▲ 《C++ Primer》 P96 指针也都支持上面的操作。

代码整洁之道--读书笔记(14)

代码整洁之道简介: 本书是编程大师“Bob 大叔”40余年编程生涯的心得体会的总结,讲解要成为真正专业的程序员需要具备什么样的态度,需要遵循什么样的原则,需要采取什么样的行动。作者以自己以及身边的同事走过的弯路、犯过的错误为例,意在为后来者引路,助其职业生涯迈上更…

hexo安装后报错hexo 不是内部或外部命令,也不是可运行的程序 或批处理文件。

hexo问题 之前利用hexo和gitee搭建了一个博客,但是最近gitee的gitpage停止服务了,便想着在github上搭建一个。 在到安装hexo这一步的时候,一直报错hexo 不是内部或外部命令,也不是可运行的程序 或批处理文件。 我的所有安装步骤和环境变量发现都没有错,反复配置后去找了一…