ECAssignment

.pdf
School
Stony Brook University**We aren't endorsed by this school
Course
CEI 572
Subject
Computer Science
Date
Dec 16, 2024
Pages
18
Uploaded by BailiffDragonfly3510
CS 3510: Design & Analysis of AlgorithmsNovember 10th 2024Programming ProblemsBonus AssignmentDue: December 3rd 2024Changelog:11/15: Removedk= 5 from the sample input for Problem 7. This was a typo since theproblem has no input ofk.11/15: The autograder now allows for 3 submissions every day rather than 3 submissions inany 24 hour period (see Ed #1215).11/15: We will accept whatever big-O you give as long as your algorithm passes the autograderwithout exceeding the time limit and the big-O runtime accurately reflects your algorithm.This includes algorithms that are less efficient, equally efficient, or more efficient than ourimplementation (see Ed #1186).
Background image
1Guidelines1.Please read this document in its entirety. It contains important information regarding whatyou are allowed to submit and what modifications you are permitted to make to the templates.2.Start early. As noted in the submission limits section, you are allowed only three submissionsevery twenty-four hours. There is no late acceptance for this assignment, and we will notincrease the number of allowed submissions as the deadline approaches.3.You are allowed to collaborate with your peers, but any code you submit must be your own.You are not permitted to share solution code or view someone else’s solution code. Anyviolations will be reported directly to the Office of Student Integrity.4.This is a new assignment and autograder. We have tested it thoroughly, but if you encounterany issues with the assignment itself, please report them on Ed Discussion as soon as possible.5.If you have anything to discuss on Ed, tag it with the “EC Assignment” tag and include thequestion number in the title.2OverviewThis programming assignment serves as extra credit toward your final grade in CS 3510. We arecurrently offering up to 3% extra credit for this assignment. You may choose to work in C++,Java, or Python. To begin the project, simply download the Solutions file from Canvas for thelanguage you wish to use. Implement each problem defined in Section 6 using the provided methodheaders. For more details and restrictions, refer to Section 4.The assignment has a total of 150 points. There are fourteen problems detailed in Section 6 thatare each worth ten points. If all tests pass for all fourteen problems, an additional ten points willbe awarded. Partial credit is awarded on the overall assignment, but each problem is all-or-nothing.This means you must pass all the test cases for a problem to earn the ten points for that problem,though you may choose to complete only a subset of the problems.To receive full credit for a problem, you must not only pass the autograder but alsoinclude an explanation and runtime analysis.Each method header has space for these detailsin the comment block above. We expect a 4-5 sentence explanation of why your algorithm works,similar to the correctness proofs we’ve done in class. We also expect a runtime analysis in big-Onotation with a 1-2 sentence justification for the provided runtime. These written submissionswill be manually graded, and no points will be awarded for a problem if the written submission ismissing.3AutograderThe autograder calls each of the methods defined in theSolutionsclass with input from our testcases. The autograder compares the output from your method to the expected output. If the
Background image
output for any test case differs from the expected result, no points will be awarded for that problem.Test cases will not be disclosed to students.The autograder also enforces a runtime limit for each individual test case. The timeout is setto three times the runtime of our reference implementation. This ensures students cannot brute-force solutions and encourages efficient implementations. If the autograder indicates that youare exceeding the time limit, consider optimizing your implementation by removing unneces-sary loops or processing. If you are certain that your solution is as optimal as possible and youare still exceeding the time limit, make a private post on Ed and we’ll take a look at your submission.The autograder only reports whether all test cases were passed for each problem. If not all testcases are passed, the autograder will indicate whether the failure was due to mismatched outputs ora timeout. If you are failing tests due to mismatched outputs, you must write your own local testsand consider edge cases.Students are allowed to share local testing tools, and we encourageyou to do so through Ed Discussion. If you share local tests, they must be in a separate file fromSolutions.py, Solutions.java, or Solutions.cpp (e.g., a wrapper program that calls methods in theSolutions files). You are never allowed to copy-and-paste someone else’s code into your Solutionsfile, but you can copy-and-paste tests that interact with the Solutions file onto your local machine.For reference and consistency in running local tests, the autograder currently uses:Python 3.10.12for Python codeg++ 11.4.0for compiling C++ codeOpenJDK 11.0.24for compiling Java code.4Submission Format and LimitsSubmit either Solutions.py, Solutions.java, or Solutions.cpp to the autograder.Theautograder will fail if more than one file is submitted or if the file is named anything other thanSolutions.py, Solutions.java, or Solutions.cpp. The autograder simply calls the methods definedinside theSolutionsclass, so you may add public or private helper methods within the class.However, do not modify any of the existing method headers.Students are limited to three submissions within any 24-hour period.Any submissionsbeyond this limit will not be graded, and the score from the previous submission will be retained.Finally, do not add any imports or includes to the Solutions files. You must work withthe imports/includes already defined, and adding any more will result in a zero for the entireassignment.5Honor CodeRead the below excerpt from the Georgia Tech Academic Honor Code. Plagiarism includes but is notlimited to copying another student’s code, copying code from websites such as Stack Overflow, andusing generative AI tools to complete the assignment. We will be checking each submission for signs
Background image
of honor code violations and any violation will be directly reported to the Office of Student Integrity.Honor Code Excerpt:Students are expected to act according to the highest ethical standards.The immediate objective of an Academic Honor Code is to prevent any Students from gaining anunfair advantage over other Students through academic misconduct. The following clarificationof academic misconduct is taken from Section XIX Student Code of Conduct, of the Rules andRegulations section of the Georgia Institute of Technology General Catalog: Academic misconductis any act that does or could improperly distort Student grades or other Student academic records.Such acts include but need not be limited to the following:Unauthorized Access:Possessing, using, or exchanging improperly acquired written orverbal information in the preparation of a problem set, laboratory report, essay, examination,or other academic assignment.Unauthorized Collaboration:Unauthorized interaction with another Student or Studentsin the fulfillment of academic requirements.Plagiarism:Submission of material that is wholly or substantially identical to that createdor published by another person or persons, without adequate credit notations indicating theauthorship.False Claims of Performance:False claims for work that has been submitted by a Student.Grade Alteration:Alteration of any academic grade or rating so as to obtain unearnedacademic credit.Deliberate Falsification:Deliberate falsification of a written or verbal statement of fact toa Faculty member and/or Institute Official, so as to obtain unearned academic credit.Forgery:Forgery, alteration, or misuse of any Institute document relating to the academicstatus of the Student.Distortion:Any act that distorts or could distort grades or other academic records.While these acts constitute assured instances of academic misconduct, other acts of academicmisconduct may be defined by the professor.
Background image
6Problem DescriptionsProblem 1: Real Estate ProfitsYou are working for a real estate firm based out of Atlanta, GA. The city has decided to buy yourproperties in Midtown in order to develop new (unaffordable) housing for Georgia Tech students.You are forced to sell your properties one by one, but the price you can sell each property isdependent on the property value of its neighbors.Each of yournproperties currently have a value ofvi, which are provided as an array of sizen.When you sell the property at positioni, you earn a profit equal tovi1·vi·vi+1. Ifi1 is out ofbounds of the array, you can assumevi1= 1. The same applies forvi+1.Your objective is to determine the maximum possible profit you could obtain by selling yourproperties to the city.Example:Input: [5,1,8,3]Output: 180Explanation: You sell the second property, obtaining a profit of 5·1·8 = 40 and leaving the array[5,8,3]. You again sell the second property, receiving 5·8·3 = 120 and leaving [5,3]. You then sellsecond property and then last remaining property, which net 20 together. The final profit obtainedis 180 and all properties have been sold.
Background image
Problem 2: Warehouse Package StackingYou finally got an internship at Amazon, congrats! Unfortunately, you have to start as a warehouseworker and work your way up. You are managing the storage of packages in the warehouse. Eachpackage has a specific width and height, and you want to stack as many packages as possible in asingle column so that each package in the stack fits within the dimensions of the package directlybelow it. More specifically, a package can only be stacked on top of another package ifboth itswidth and height are strictly smaller than the package below it.Bezos will only promote you if you are good at this task, so return themaximum numberof packages you can stack up.Note: You cannot rotate the packages.Input Format:You are given an arraypackageswhere each entrypackages[i] is a tuple[widthi,heighti] representing the width and height of thei-th package.Example 1:Input:packages= [[5,4],[6,4],[6,7],[2,3]]Output: 3Explanation: The maximum number of packages you can stack is 3 ([2,3][5,4][6,7]).Example 2:Input:packages= [[8,9],[1,1],[6,10],[3,4],[5,8],[2,3]]Output: 5Explanation: The maximum number of packages you can stack is 5 ([1,1][2,3][3,4][5,8][8,9]).
Background image
Problem 3: Building BlocksTwo toddlers started learning Dynamic programming in kindergarten to start early on theirCS interview preparation. They decided to take a break and play with some building blocks. Theyeach have a sequence of blocks of varying heights that may not be sorted, ie,blocks1[a1, a2, .., an]andblocks2[b1, b2, .., bn]. They both have the same number of blocks. They each want a sequenceof blocks withstrictly increasing heightsto build a nice-looking structure.As their sequence of blocks may not be sorted they decide to do this by exchangingcorre-sponding blocks only with each other, ie, they will only swapaiwithbito get a strictlyincreasing sequence. They want to know the minimum number of swaps they need to do to achievethis. They recognize that they need to use DP to solve this, but can’t come up with an efficientsolution, so they ask you. Please provide an efficient DP solution to help them. If no solution ispossible return1.ExampleInput:N = 4, blocks1 = [3, 4, 5, 4], blocks2 = [1, 2, 3, 8]Output: 1Explanation: They can swap their last blocks to achieve strictly increasing sequences.Afterswapping their last blocks, they will haveblocks1 = [3, 4, 5, 8], blocks2 = [1, 2, 3, 4].
Background image
Problem 4: Modular Two SumGiven a list of integers A: [a1, a2, ..., an] and an integerk, count all pairs of integers whose sum isdivisible byk. In mathematical terms, count pairs wherek|(ai+aj)andi < j. You may assumek2 and len(A)2.A brute force approach entails summing all possible pairs of the list’s integers and checking theirdivisibility byk, running inO(n2).Produce a more efficient algorithm utilizing properties ofmodular arithmetic.Example:Input:A= [5,7,1,10,4,119]k= 6Output: 5Explanation:In the given list, there are five pairs with a sum divisible by 6.6|(5 + 7)6|(5 + 1)6|(7 + 119)6|(10 + (-4))6|(1 + 119)
Background image
Problem 5: Maximum Magic Power PathImagine a magical kingdom represented by an enchanted forest withnmystical locations (nodes)numbered from 0 ton1.Each locationiholds a unique magical energy level given by theinteger array energies where energies[i] represents the magical power of locationi. The forest pathsconnecting these locations are enchanted, with each path taking a certain amount of time to travel.The paths are described in a 2D integer array paths, where each entry paths[j] = [uj,vj,timej]indicates a magical path between locationsujandvj, withtimejseconds required to travel thispath. All paths are bi-directional, allowing travel in both directions. The kingdom has an ancienttime-binding spell, maxTime, which limits how long a traveler can spend journeying in the forest.Avalid journeyin the enchanted forest is a path that:Starts and ends at location 0,Takes at mostmaxTimeseconds to complete,May revisit locations as often as needed.Thepowerof a journey is the sum of the magical energies of the unique locations visited alongthat journey (each location’s energy contributes only once per journey). Write an algorithm to findthe maximum possible power of any valid journey.Note:Due to the ancient protections on eachlocation, each one is connected by at most four paths.Example:01231010150321043Input:energies = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49Output: 75Explanation: One example route is 01030. The total time is 10 + 10 + 10 + 10 =40, which is within the limit of 49. The visited locations are 0, 1, and 3, giving a total power of 0 +32 + 43 = 75.
Background image
Problem 6: Divide the HarvestYou have a long row of harvest baskets, each filled with a certain quantity of fruit. The quantity ineach basket is given by the arrayquantity. You want to share the baskets with yourkneighbors,so you’ll divide the row into exactlyk+ 1 portions by makingkcuts. Each portion will consist ofconsecutive baskets.To be fair, you want to ensure that the portion with thesmallest total fruit quantityisas large as possible. However, to keep the peace, you’ll take the portion with thesecond-smallesttotal fruit quantityfor yourself, while giving the others the remaining portions.Find the highest possible quantity of fruit in the portion you can keep, assuming you alwaystake the second-smallest portion after dividing. Assume that 1k < len(quantity).Example:Input:quantity = [1,2,3,4,5,6,7,8,9], k = 5Output: 6Explanation: You can divide the harvest into[1,2,3],[4,5],[6],[7],[8],[9]. The portionwith the least fruit quantity has 6, so you take the next one which also has 6.
Background image
Problem 7: Coloring SidewalksWoohoo! All the sidewalk construction around campus is finally finished. However, as the laststep, GT authorities want to add more color to the new sidewalks by painting them gold, white,or blue. Withnadded sidewalks, they task you with painting the sidewalks one of the 3 col-ors.The time to color each sidewalk a certain color is different, which is given to you by anx 3 matrix. For example, time[0][0] represents the number of minutes required to color side-walk 0 gold; time[1][2] represents the number of minutes required to color sidewalk 1 blue; and so on.Your job is to color all the sidewalks such that no two adjacent sidewalks are the same color.Being the busy student you are, you want to minimize the amount of time you spend painting thesidewalks. Determine the minimum time required to satisfy the required coloring.Example:Input:time = [[3,2,5],[3,4,6],[3,1,2]]Output: 6Explanation: Given a row of 3 sidewalks, the shortest amount of time to color the row such thatno two adjacent tiles are the same color is to color sidewalk 0 white (2 minutes), sidewalk 1 gold (3minutes), and sidewalk 2 white (1 minute), giving a total of 6 minutes.
Background image
Problem 8: Chemical ConcoctionsA scientist recently discovered some new chemicals. There are at most 26 new chemicals, and eachone is labeled with a distinct letter from ‘a’-’z’ (all lower case). The scientist needs to find thenatural ordering of these chemicals, but the only hint is a formula sheet. The sheet contains a listof non-empty chemical formulas sorted based on the special ordering. Every chemical found by thescientist is guaranteed to be on the sheet. There are two known rules about the natural order givenbelow.For two formulas X and Y, X comes before Y if either condition holds true:The first chemical in X is less than the corresponding chemical in Y.Ex: X=“abp” and Y=“abi”. Assuming that X<Y, this means that ‘p’<‘i’.X containsnchemicals which are the exact same as the firstnchemicals in Y, but X usesfewer chemicals than Y.Ex: X=”zpeos” and Y=”zpeosd”. X<Y since the first 5 chemicals of X and Y match,but Y contains more chemicals.Your goal is to help the scientist find a valid ordering. If multiple orderings exist, return any one ofthem. If no ordering is possible, return an empty string.Example:Input: [“bz”, “buzz”, “fizz”, “fz”, “zi”]Output: “bfizu” or “bifzu”Explanation:from “bz” and “buzz”, we know that ‘z’<‘u’from “buzz” and “fizz”, we know that ‘b’<‘f’from “fizz” and “fz” we know that ‘i’<‘z’From “fz” and “zi” we know that ‘f’<‘z’Using the conditions discovered by comparing the words, we find that two possible valid orderingsare “bfizu” or “bifzu”.
Background image
Problem 9: Maximum Sum of Non-Adjacent SubsequenceYou are given an integer arraynumscontainingnintegers. You need to select a subsequence ofelements fromnumssuch that no two elements in the subsequence are adjacent innums. Your goalis to maximize the sum of the selected elements.Return the maximum possible sum of the non-adjacent subsequence.Example:Input: nums = [3,2,7,10]Output: 13Explanation: The optimal solution is to pick 3 and 10, resulting in a maximum sum of 3 + 10 = 13.
Background image
Problem 10: DigitGPTAs part of their work at ClosedAI, Scam Altman and Melon Musk have developed a new modelcalled DigitGPT that generates a random string of lengthmas output whenever prompted. Eachof the characters in this string is a number between 0 and 9.Dr. Ilya Cutskewer recently left ClosedAI due to conflicts with management and, in order to takerevenge, has developed a bot that randomly erases an even number of characters in DigitGPT’soutput. Specifically, whenever DigitGPT is prompted, Dr. Cutskewer may launch an attack thatreplaces an even number of characters (possibly 0) withsymbols (without affecting the order ofthe remaining digits) before the output reaches the end user.Internally, while ClosedAI engineers are being overworked to prevent these attacks from affectingany more users, Scam and Melon have placed a bet on the strings generated by DigitGPT. Fora given string, Scam and Melon will take turns (with Scam going first) replacingsymbols withdigits between 0 and 9, stopping when there are no moresymbols in the string. Melon will replaceScam as CEO if, after all the turns, the sum of the digits in the first half of the string is equal tothe sum of the digits in the second half of the string. In any other case, Scam remains CEO. Assum-ing both Scam and Melon are perfect logicians and play optimally, will Melon replace Scam as CEO?Given the number of characters in the string generated by DigitGPT and the string of lengthm(wheremis even) generated by DigitGPT following Dr. Cutskewer’s attack (this string will containa combination of digits andsymbols such that the number ofsymbols is even), return whetheror not Melon will replace Scam as CEO.Example 1:Input:42433Output: TrueExample 2:Input:6000**0Output: FalseExplanation: In example 1, there are no remaining moves and the sum of the digits in thefirst half is equal to the sum in the second half. In example 2, Scam can replace anysymbol witha 1, preventing the sum from being equal.
Background image
Problem 11: Building a Brick WallYou are constructing a wall around your house using bricks of different lengths. Each type of brickis available in unlimited quantities, and you want the total wall length to cover three sides of yourhouse, which is given by the length l.Determine the number of unique ways in which you can build this wall using the availablebricks.If you cannot make the wall with the given lengths of bricks, return 0.Example:Input: B = [1,2,5];l = 6Output: 5Explanation: Given 3 different lengths of bricks 1,2,5. Given a target wall length of 6. There areexactly 5 ways to make this wall:6 = 5+16 = 2+2+26 = 2+2+1+16 = 2+1+1+1+16 = 1+1+1+1+1+1
Background image
Problem 12: Stuck in an ArchipelagoYou work for an infrastructure company which is building bridges for a nation-state located inan archipelago. The archipelago is prone to many disasters like hurricanes, and tsunamis; thesemay take out bridges between the islands of the archipelago. The government wants you to buildbridges such that even if one bridge from an island to another island is destroyed, there will alwaysbe another bridge that can be crossed to leave a group of islands.You are on a subteam tasked with finding needed bridges which are bridges where if any one ofthem are removed, it will disconnect some island from some other island.You’re given the number of islands, and the number of bridges between those islands. Followingthat, you’ll be given pairs of numbers, each represents a bridge from the island with the id of thefirst number to the id of the second number. You should print out, the number of needed bridgesfollowed by their values.Example:Input:n= 4, m= 4, E={(0,1),(1,2),(2,0),(1,3)}Output:{(1,3)}Explanation: This is because (1,3) is the only bridge that, if removed, would disconnect someislands from the rest. All other edges have redundant paths, ensuring connectivity even if they areremoved.
Background image
Problem 13: Search EngineerYou are a smart student at Georgia Tech and well-known for your skills in algorithms. One of yourold friends has started his company which is building a super-fast search engine. He asks you foryour help in optimizing his search engine. Now, you are faced with the following task:You are given two stringstextandpattern. You need to find the number of distinct subsequencesoftextwhich are equal topattern.A subsequence of the stringais defined as a sequence that can be obtained fromaby deletingsome elements (possibly none), without changing the order of the remaining elements.Example:Input:text=rabbbitandpattern=rabbitOutput: 3Explanation: As shown below, there are 3 ways in which you can generaterabbitfromrabbbit.ra)b(bbitrab)b(bitrabb)b(it
Background image
Problem 14: Buzz’s BeesBuzz has recently decided to pick up beekeeping!He hasNworker bees and wants to estab-lish a communication network for the bees to share the latest pollen locations with each other.Theithbee is located at a distinct position (xi, yi) in the field. Establishing a connection betweenbeeiandjcosts (xixj)2+ (yiyj)2. Can you help Buzz calculate the minimum cost needed tobuild a network connecting allNbees?ExampleInput:N = 3, locations = [(1, 4), (3, 2), (0, 3)]Output:10Explanation: Build a connection between(1, 4)and(0, 3)for cost 2 and a connection between(1, 4)and(3, 2)for cost 8.
Background image