Khan Academy Algorithms List

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

The flow chart below visualizes an algorithm to generate the Fibonacci numbers, a famous mathematical sequence. If the variable max is set to 5, what would be displayed as a result of executing this algorithm?

1 2 3 5 8

The two algorithms below are both intended to calculate the sum of cubes from 111 to n, where n is any positive integer. For example, if n is 333, the algorithms should calculate a sum of 363636, from 1^3 + 2^3 + 3^31 3 +2 3 +3 3 1, start superscript, 3, end superscript, plus, 2, start superscript, 3, end superscript, plus, 3, start superscript, 3, end superscript. Algorithm 1: i ← n sum ← 0 REPEAT n TIMES { sum ← sum + (i * i * i) i ← i - 1 } Algorithm 2: i ← 1 sum ← 0 REPEAT n TIMES { sum ← sum + (i * i * i) i ← i + 1 } Which statements best describe the behavior of the algorithms?

Both algorithms calculate the correct sum.

A software engineer is developing a new operating system. The operating system has to make a decision when it sees an application taking a long time to finish executing an instruction. Should the operating system force quit the application, assuming it will run forever? Or can the operating system detect that the application will finish processing, if it has a bit more time? The engineer does some research and discovers that this is an undecidable problem. What are the implications of the problem being undecidable?

The problem may be solvable in some cases, but there is no algorithm that will solve the problem in all cases.

A company is developing a tool to detect "unreachable code": code in a program that will never be executed because no paths ever lead to that line of code. They want to release the tool with the promise that it will "find and delete 100% of the unreachable code in your codebase!" Unfortunately, one of the programmers does some research and realizes that determining whether a line of code is unreachable is an undecidable problem. What are the consequences of the problem being undecidable?

The programmers can come up with an algorithm that correctly determines unreachable code most of the time, but it will not correctly identify unreachable code in all cases.

Rania plans to build a pyramid out of concrete blocks. To help them decide how many blocks to buy, they come up with this algorithm for a pyramid of a given height. Start by setting total to 0 and level to 1. Repeat for each level of pyramid: Multiply n by itself and store result. Add result to total. Display the final total. Assuming height represents the pyramid height, which of these correctly expresses that algorithm in pseudocode?

total ← 0 level ← 1 REPEAT UNTIL (level > height) { result ← n * n total ← total + result level ← level + 1 } DISPLAY(total)

The flow chart below visualizes an algorithm to generate the "hailstone sequence", an interesting series of numbers. If the variable n starts off as 5, what would be displayed as a result of executing this algorithm?

16 8 4 2 1

Silas develops this algorithm to compute the calories burned for an activity for a given number of minutes and body weight: If the activity is running, compute caloriesPerMin by dividing weight by 10.5 If the activity is walking, compute caloriesPerMin by dividing weight by 15.5 Compute numCalories by multiplying caloriesPerMin by numMinutes He implements the algorithm in an app, and users soon ask for the ability to compute the total calories for multiple sessions of walking or running. What structure must be added to the original algorithm so that it can compute the total across multiple sessions?

Iteration

A statistician developed this procedure to calculate the "variance" of a list of numbers. The variance is a statistical quantity that corresponds to the average of the sum of the squared differences of each number from the mean. As input, the procedure takes a list of numbers and its mean: PROCEDURE calculateVariance(numbers, mean) { count ← 0 sumSquaredDiffs ← 0 FOR EACH num IN numbers { diff ← (num - mean) squaredDiff ← diff * diff sumSquaredDiffs ← sumSquaredDiffs + squaredDiff count ← count + 1 variance ← sumSquaredDiffs / count } RETURN variance } The statistician verifies the procedure outputs the variance correctly, but they still want to improve the efficiency of the procedure by reducing the number of operations required. Which change will reduce the most number of operations while still outputting a correct answer?

Moving the calculation of variance to be after the loop (but before the return)

A university library contains 30,000 books. One of the librarians is developing a program that can search through a list of those books, sorted by their title, to determine whether they have a particular title. They need to decide whether to use the linear search or binary search algorithm. Which of the following statements are true about those algorithms? I. Binary search is more efficient than linear search on sorted lists. II. Linear search is more efficient than binary search on sorted lists. III. Binary search is more efficient than linear search on both sorted and unsorted lists. IV. Linear search and binary search are equally efficient on all types of lists.

Only I

Farrah develops an algorithm that figures out how to pack variously sized boxes into containers. The algorithm comes up with this packing for 6 boxes into 2 containers:

She tries out the algorithm on increasing numbers of boxes, records the steps it takes, and comes up with this table: Number of boxes Steps 6 64 7 128 8 256 9 512 Based on the table, which of the following statements describe the run time for this algorithm? 👁️Note that there are 2 answers to this question.

Aliya implements an algorithm that generates a "munching square" like this one: She generates squares of various sizes and counts the number of steps required each time. Her findings are summarized in this table: Square size Steps 6 36 12 144 24 576 48 2304 Based on the table, which of the following statements describe the run time for this algorithm? 👁️Note that there are 2 answers to this question.

The algorithm runs in polynomial time. The algorithm runs in reasonable time.

InstaGrocery is a service that delivers groceries to people's homes. Their service, website, and mobile app are powered by a variety of algorithms. Which algorithm's runtime is most likely to be improved by the use of a heuristic?

Calculating a fast route for the driver to deliver bagged groceries to many different customers

The United States Postal Service (USPS) delivers nearly 200 million pieces of mail every day. Their website and internal operations are powered by many algorithms. Which algorithm's runtime is most likely to be improved by the use of a heuristic?

Calculating an efficient route for a delivery carrier through a city, considering factors like parking space and mail volume

An online app for playing Chess utilizes a variety of algorithms. Their software engineers would like the algorithms to run in under a second so that users have a great experience. Which algorithm's runtime is most likely to be improved by the use of a heuristic?

Choosing a good move when the computer is playing against the human

Khan Academy uses an algorithm to determine whether to show or hide user-created programs to other users. This flow chart shows a simplified version of that algorithm: Which pseudocode is equivalent to the algorithm in the flowchart?

IF (creatorAge < 13 OR (adminLevel = 0 AND spamScore ≥ 2.0)) { isHidden ← true } ELSE { isHidden ← false }

An online shopping site uses the following algorithm to decide what related products to show on each product page. Which pseudocode is equivalent to the algorithm in the flowchart?

IF (itemSimilarity > 0.9 OR userSimilarity > 0.8 OR updatedModel = true) { showRelated ← true } ELSE { showRelated ← false }

A restaurant delivery app uses the following algorithm to choose the restaurants it features to each user. Which pseudocode is equivalent to the algorithm in the flowchart?

IF (openNow = true AND milesAway < 5 AND reviews > 3.5) { showFeatured ← true } ELSE { showFeatured ← false }

An algorithm will be used to calculate the difference between the smallest and largest values in a list. For the list of [10, 3, 5, 6], it should calculate a difference of 7. There are two proposals for the algorithm: Algorithm 1: Set minVal to the first value in the list and maxVal to the last value in the list. Iterate through each number in the list. If the number is greater than maxVal, store it in maxVal. If the number is less than minVal, store it in minVal. After loop, set maxDiff to the difference between maxVal and minVal. Algorithm 2: Set minVal to 1000 and maxVal to 0. Iterate through each number in the list. If the number is greater than maxVal, store it in maxVal. If the number is less than minVal, store it in minVal. After loop, set maxDiff to the difference between maxVal and minVal. Which of these statements are true about these algorithms? I. Algorithm 1 does not work on lists where the smallest value is at the start of the list or the largest value is at the end of the list. II. Algorithm 2 does not work on lists that contain all negative numbers or all numbers over 1000.

II only

The two algorithms below are both intended to calculate the product of squares from 1 to n, where n is any positive integer. For example, if n is 333, the algorithms should calculate a product of 363636, from 1^2 * 2^2 * 3^21 2 ∗2 2 ∗3 2 1, start superscript, 2, end superscript, times, 2, start superscript, 2, end superscript, times, 3, start superscript, 2, end superscript. Algorithm 1: i ← n product ← 0 REPEAT n TIMES { product ← product * (i * i) i ← i - 1 } Algorithm 2: i ← 0 product ← 1 REPEAT n TIMES { product ← product * (i * i) i ← i + 1 } Which statements best describe the behavior of the algorithms?

Neither algorithm calculates the correct product.

An algorithm will be used to count how many numbers in a list are multiples of either 5 or 10. For the list of [5, 3, 2, 10, 20, 7], it should count 3 numbers (5, 10, 20). There are two proposals for the algorithm: Algorithm 1: Set value of count to 0. Iterate through each number in the list. If the current number is a multiple of 5 and a multiple of 10, increment count by 1. Algorithm 2: Set value of count to 0. Iterate through each number in the list. If the current number is a multiple of 5, increment count by 1. Then, if the current number is a multiple of 10, increment count by 1. Which of the following best describes the behavior of these algorithms?

Neither algorithms will output the correct count on all inputs, due to issues with under-counting or over-counting multiples.

A programmer develops the procedure hasElevenEleven(), which should return true if it ever finds a 1 next to a 1 somewhere. For example, hasElevenEleven([7, 1, 1]) should return true, but hasElevenEleven([1, 7, 1]) should return false. PROCEDURE hasElevenEleven(numbers) { i ← 1 REPEAT UNTIL (i = (LENGTH(numbers) - 1)) { IF (numbers[i] = 1 AND numbers[i + 1] = 1) { RETURN true } i ← i + 1 } RETURN false } The programmer tests it with hasElevenEleven([1, 0, 1, 1, 0]) and sees that it does indeed return true. Can the programmer conclude that the procedure works correctly for all inputs?

No, they've only verified that it works for that test case. Additional analysis and reasoning is necessary.

A programmer develops the procedure makeNumsList() to generate lists of numbers starting at start and ending with end. For example, makeNumsList(4, 7) should return [4, 5, 6, 7]. PROCEDURE makeNumsList(start, end) { numsList ← [] numTimes ← (end - start) + 1 num ← 1 REPEAT numTimes TIMES { APPEND(numsList, num) num ← num + 1 } RETURN numsList } The programmer tests it with makeNumsList(1, 4) and sees a return value of [1, 2, 3, 4]. Can the programmer conclude that the procedure works correctly for all inputs?

No, they've only verified that it works for that test case. Additional analysis and reasoning is necessary.

A data scientist develops an algorithm for analyzing social media data. They're writing a blog post about it, and are hoping that other data scientists will try out the algorithm on their own data. They're debating whether to express the algorithm in natural language, flow charts, pseudocode, or Python, a general-purpose programming language. Which of these is a good argument for expressing the algorithm in Python?

Python can be run on any computer that has a Python interpreter, so others can try out the algorithm with their own data and not worry about translating the algorithm correctly to a language.

Han develops an algorithm to compute the average amount of time that users watch a particular video on Khan Academy. He then realizes that the average is very low, due to a large number of times with duration "0" or "1", and decides that the algorithm should ignore those durations. What structure must be added to the algorithm so that it does not consider those short durations when computing the average?

Selection

The following algorithm computes the maximum score for a list of final exam scores. Initialize a variable max to the first score in the list. For each score in the list, compare the score to max. If score is greater than max, store score in max Return max. Which building blocks are involved in this algorithm? 👁️Note that there may be multiple answers to this question.

Selection Iteration Sequencing

The following algorithm computes the average height for a list of basketball player heights. Initialize a variable sum to 0. For each height in the list: Convert height from feet & inches format to total inches Add height to sum. Return sum divided by the total number of heights. Which building blocks are involved in this algorithm? 👁️Note that there may be multiple answers to this question.

Sequencing Iteration

The following algorithm computes the standard deviation of all the scores on the AP Computer Science Principles exam: Compute the average of all the scores. For each score, compute the square of its difference from the average. Sum the values from step 2. Divide the sum by the number of scores. Take the square root. Which building blocks are involved in this algorithm? 👁️Note that there may be multiple answers to this question.

Sequencing Iteration

Meredith implements a "graph coloring" algorithm, which comes up with colors for graph vertices such that no neighboring vertices share the same color. The algorithm outputs graph colorings like this one: Using a palette of just 3 colors, she runs the algorithm on graphs with varying amounts of vertices and records how long it takes. Her findings are summarized in this table: Graph vertices Steps 4 81 6 729 8 6561 Based on the table, which of the following statements describe the run time for this algorithm? 👁️Note that there are 2 answers to this question.

The algorithm does not run in reasonable time. The algorithm runs in superpolynomial time.

Yuto implements an algorithm for finding the "greatest common divisor" of two numbers. For the numbers 54 and 24, it finds a greatest common divisor of 6. He counts the number of steps required by the algorithm for numbers of increasing digit length and comes up with this table: Number of digits Steps 2 4 3 6 4 8 5 10 6 12 Based on the table, which of the following statements describe the run time for this algorithm? 👁️Note that there are 2 answers to this question.

The algorithm runs in polynomial time. The algorithm runs in reasonable time.

Kora implements an algorithm for determining whether a list has duplicate values. She counts the number of steps required by the algorithm for increasing list lengths and comes up with this table: List length Steps 6 15 8 28 10 45 12 66 Based on the table, which of the following statements describe the run time for this algorithm? 👁️Note that there are 2 answers to this question.

The algorithm runs in reasonable time. The algorithm runs in polynomial time.

A software engineer at a mapping company is tasked with coming up with an algorithm to solve a new problem. The engineer is nervous about whether they'll be able to solve it. Which of these outcomes is the least likely?

The engineer may discover that it the algorithm is only solvable in a programming language that their company does not use.

A security engineer is developing antivirus software that detects when downloaded programs look similar to known viruses. They would like the software to be able to detect viruses that it's never seen before, by predicting whether or not a program will ever execute malicious code. After a bit of research, the engineer realizes that virus detection is an undecidable problem. What are the consequences of the problem being undecidable?

The engineer might come up with an algorithm that correctly predicts the execution of malicious code in some cases, but the algorithm will not be correct all of the time.

A high school provides email addresses to freshman students. The email system typically assigns an email address in the format "[email protected]". However, if a student has the same name as a previous student, the system assigns them a different format. In order to figure out whether an email address is already assigned, the system does a binary search through its list of existing email addresses. Which of these statements is true?

The list of email addresses must be sorted for binary search to work.

ScootALot is a scooter rental service. At the end of each day, they hire contractors to pick up scooters and distribute them optimally around the city. The distribution algorithm considers all the possible locations for the scooters, compares that to the density of customers, and comes up with the optimal location for each scooter. As the company becomes more popular, they realize their algorithm is taking an unreasonable amount of time to come up with optimal scooter locations. What is the best way to improve the run time of the algorithm?

Use a heuristic-based algorithm that suggests good locations for the scooters.

Hearify is an online music streaming service. They want to introduce a new feature that automatically generates 60-minute long playlists of popular music in different genres. They want each playlist to be exactly 60 minutes long and to include the most highly rated songs possible. They develop the feature but discover that it takes a long time for the computer to consider all the possible combinations of songs, and that extra time costs them money. Can the run time of the feature be improved?

Yes, they can speed up the run time by using a heuristic to output a playlist that is not optimal, but close enough.

The goal of the procedure computeAverage is to calculate the average of a list of numbers, ignoring any 0 values. For example, if given the list [0, 1, 3, 5], it should return the number 3. PROCEDURE computeAverage(numbers) { total ← 0 count ← 0 FOR num IN numbers { IF (num ≠ 0) { total ← total + num count ← count + 1 } ELSE { RETURN total/count } } RETURN total/count } A programmer tests the procedure with various inputs and finds multiple cases where it does not produce the expected output. Which calls to computeAverage() return an incorrect average? 👁️Note that there are 2 answers to this question.

computeAverage([22, 0, 49, 8]) computeAverage([22, 9, 0, 17])

A programmer comes up with an algorithm for reversing a list of strings. This table shows how many steps the algorithm requires for different list lengths. List length Steps 10 5 50 25 100 50 500 250 Which function best describes how the number of steps changes as the list length (n) increases?

n/2

A mathematician comes up with an algorithm to search a matrix for a value. This table shows how many steps the algorithm requires for different matrix sizes: Matrix size Steps 2 4 4 16 6 36 8 64 Which function best describes how the number of steps changes as the matrix size (n) increases?

n^2

A mathematician comes up with an algorithm for multiplying two matrices together. This table shows how many steps the algorithm requires for different matrix sizes: Matrix size Steps 1 1 2 8 3 27 4 64 5 125 Which function best describes how the number of steps changes as the matrix size (n) increases?

n^3

The flow chart below visualizes the steps of an algorithm: What would be displayed as a result of executing this algorithm?

10

An online store manages an inventory of millions of products. On their front page, they show customers products related to the ones they've recently bought. This procedure comes up with a list of similar products for a given list of products: PROCEDURE findSimilarProducts(products) { similarProducts ← [] FOR EACH product IN products { similarProduct ← calcSimilar(product) APPEND(similarProducts, similarProduct) } RETURN similarProducts } The calcSimilar() procedure takes 2 minutes to return a result, as it needs to do a complicated series of database lookups and mathematic operations. The other operations, creating the empty list and appending items to the list, only take a few nanoseconds. If the store calls the procedure on a list of 5 products, approximately how long will it take to complete?

10 minutes

An app for electric car owners includes a feature that shows them the charging station that's the nearest to them. To calculate that, the app first finds the 10 closest stations according to their beeline distance from the user address. It then uses the procedure below to calculate the driving distance to each station and returns the station with the shortest distance. PROCEDURE findClosestStation(address, stations) { minDistance ← calcDrivingDistance(address, stations[1]) closestStation ← stations[1] ind ← 2 REPEAT UNTIL (ind > LENGTH(stations)) { drivingDistance ← calcDrivingDistance(address, station) IF (drivingDistance < minDistance) { minDistance ← drivingDistance closestStation ← stations[ind] } ind ← ind + 1 } RETURN closestStation } The call to calcDrivingDistance() takes 3 seconds to return a result, as the driving directions algorithm requires searching through many possible routes to calculate the optimal route. The other operations, like incrementing the index and comparing the distances, take only a few nanoseconds. If the app calls the procedure on a list of 10 stations, approximately how long will it take to complete?

30 seconds

A photo-editing program includes a "batch compression" utility, which gives users the ability to compress many images at once. This procedure takes the image filenames as input, compresses each image, and reports the total size of the newly compressed images: PROCEDURE compressImages(images) { totalSize ← 0 FOR image IN images { newSize ← compressImage(image) totalSize ← totalSize + newSize } RETURN totalSize } The call to compressImage() takes 10 seconds to complete, as the image compression algorithm requires a series of mathematical operations running on every pixel. The other operations, like incrementing the total size, take only a few nanoseconds. If the program calls the procedure on a list of 6 images, approximately how long will it take to complete?

60 seconds

The two algorithms below are both intended to calculate the sum of squares from 1 to n, where n is any positive integer. For example, if n is 333, the algorithms should calculate a sum of 141414, from 1^2 + 2^2 + 3^21 2 +2 2 +3 2 1, start superscript, 2, end superscript, plus, 2, start superscript, 2, end superscript, plus, 3, start superscript, 2, end superscript. Algorithm 1: i ← 1 sum ← 0 REPEAT n TIMES { sum ← sum + (i * i) i ← i + 1 } Algorithm 2: i ← 1 sum ← 0 REPEAT n TIMES { sum ← sum + (i + i) i ← i + 1 } Which statements best describe the behavior of the algorithms?

Algorithm 1 calculates the correct sum, but algorithm 2 does not.

Which of these statements about algorithms is not true?

An algorithm that uses a heuristic will come up with the optimal solution more quickly than an algorithm that does not.

The two procedures below are both intended to classify numbers in a list in relation to a target number. They should each return a list with 3 numbers: the amount of numbers in the list larger than the target number, the amount of numbers in the list smaller than the target number, and the amount of numbers equal to the target number. Procedure #1: PROCEDURE classifyNumbers(numbers, targetNum) { numBigger ← 0 numSmaller ← 0 FOR EACH num IN numbers { IF (num > targetNum) { numBigger ← numBigger + 1 } ELSE { IF (num < targetNum) { numSmaller ← numSmaller + 1 } } } numEqual ← LENGTH(numbers) - (numBigger + numSmaller) RETURN [numBigger, numEqual, numSmaller] } Procedure #2: PROCEDURE classifyNumbers(numbers, targetNum) { numBigger ← 0 numSmaller ← 0 numEqual ← 0 FOR EACH num IN numbers { IF (num > targetNum) { numBigger ← numBigger + 1 } ELSE { IF (num < targetNum) { numSmaller ← numSmaller + 1 } ELSE { numEqual ← numEqual + 1 } } } RETURN [numBigger, numEqual, numSmaller] } Which of the following best describes the two procedures?

Both procedures return the correct list, but procedure #2 requires more operations on average than procedure #1.

The two procedures below are both intended to find a target string in a list of strings. They should return true if they find the string and false if they do not. Procedure #1: PROCEDURE findString(strings, targetString) { index ← 1 foundString ← false REPEAT UNTIL (index > LENGTH(strings)) { IF (strings[index] = targetString) { foundString ← true } index ← index + 1 } RETURN foundString } Procedure #2: PROCEDURE findString(strings, targetString) { index ← 1 REPEAT UNTIL (index > LENGTH(strings)) { IF (strings[index] = targetString) { RETURN true } index ← index + 1 } RETURN false } Which of the following best describes the two procedures?

Both procedures return the correct value, but procedure #1 requires more operations on average than procedure #2.

A programmer wants to present their idea for an algorithm at a company meeting. They're debating whether to express the algorithm in flow charts, pseudocode, or a programming language. Which of these is a good argument for expressing the algorithm in a flow chart at the company meeting?

Flow charts can require less technical knowledge to understand than pseudocode or programming languages.

An algorithm will be used to decide whether every number in a list is either a 4 or a 5. There are two proposals for the algorithm: Algorithm 1: Set only45 to false. Iterate through each number in the list. If the number is not equal to 4 and not equal to 5, set only45 to false. Otherwise, set only45 to true. Algorithm 2: Set only45 to true. Iterate through each number in the list. If the number is not equal to 4 and not equal to 5, set only45 to false. Which of these statements are true about these algorithms? I. Algorithm 1 does not work on lists where a number other than 4 and 5 occurs before the last number. II. Algorithm 2 does not work on lists which contain entirely 4s or entirely 5s.

I only

Serena operates a security camera that stores still images in timestamped filenames. The camera can generate thousands of images each day, and she needs a way to find the image corresponding to a particular timestamp. She comes up with this algorithm: Start with a list of the image filenames, sorted from oldest to newest. Set min to 1 and max to the number of images. Set index to the average of max and min, rounded down so that it is an integer. Check the filename located at that index in the list. If the filename equals the desired timestamp, the search is done! Exit the algorithm. If the filename is older than the desired timestamp, set min to be one larger than index. If the filename is newer than the desired timestamp, set max to be one smaller than index. Go back to step 2. Which statements are true about this algorithm? 👁️Note that there are 2 answers to this question.

It implements a binary search. It is more efficient than a linear search.

Makayla is developing software for an animal shelter. After some research, she comes up with this algorithm for calculating the number of daily calories required for a dog: Calculate the Resting Energy Requirement (RER) by raising the dog's weight to the 3/4 power and multiplying the result by 70 If the dog is neutered, multiply RER by 1.6 Otherwise, multiply RER by 1.8 After verifying the algorithm comes up with a reasonable number for a single dog, she decides to extend it to compute the total calories needed for all the dogs in the shelter each day. What structure must be added to the original algorithm so that it can compute the calories for multiple dogs?

Iteration

Sariah is writing a research paper for literature class where she must cite many sources. She decides to make a tool to automate the citation process, and comes up with the following algorithm for citing a book: Split author name into first name and last name. Combine last name, comma, first name, and period. Combine title with period, and wrap in italics style. Combine publisher, comma, year published, and period. Combine strings from steps 2-4. After using the algorithm successfully for a single book, she decides to extend it to generate citations for all of her books at once. What structure must be added to the original algorithm so that it can operate on multiple books?

Iteration

A school IT administrator develops a procedure that compares two lists of grades and returns the percentage of grades in the second list that are higher than the related grade in the first list. They plan to use the procedure to measure student improvement. As input, the procedure takes two lists of numbers: PROCEDURE calcPercentGreater(list1, list2) { numGreater ← 0 ind ← 1 REPEAT UNTIL ( ind > LENGTH(list1) ) { IF (list2[ind] > list1[ind]) { numGreater ← numGreater + 1 percentGreater ← numGreater / LENGTH(list1) } ind ← ind + 1 } RETURN percentGreater } The administrator verifies the procedure outputs the percentage correctly, but they still want to improve the efficiency of the procedure by reducing the number of operations required. Which change will reduce the most number of operations while still outputting a correct answer?

Moving the calculation of percentGreater to be after the loop (but before the return)

A programmer develops the procedure maxPairSum() to compute the sum of subsequent pairs in a list of numbers and return the maximum sum. For example, for a list of [2, 3, 4, 1], the sums of subsequent pairs are 5 (from 2 + 3), 7 (from 3 + 4), and 5 (from 4 + 1). The procedure should return the maximum sum of 7. PROCEDURE maxPairSum(numbers) { i ← 1 maxSum ← 0 REPEAT UNTIL (i = LENGTH(nums)) { sum ← nums[i] + nums[i + 1] IF (sum > maxSum) { maxSum ← sum } i ← i + 1 } RETURN sum } The programmer tests it with maxPairSum([5, 4, -4, 3, 2]) and sees a return value of 9. Can the programmer conclude that the procedure works correctly for all inputs?

No, they've only verified that it works for that test case. Additional analysis and reasoning is necessary.

Ryland is creating an article about commonly used compression algorithms for an online educational site. He's debating whether to express each algorithm in natural language, flow charts, pseudocode, or C++, a general-purpose programming language. Which of these is a good argument for expressing the algorithm in pseudocode?

Pseudocode doesn't depend on the syntax and subtleties of a particular programming language, so his readers will be able to understand it as long as they know at least one language.

Akuchi develops an algorithm that counts the number of words used in an essay. Now they've been asked to extend the algorithm to ignore common words (like "the" and "to"). What structure must be added to the algorithm so that it does not count common words?

Selection

An online store uses an algorithm that calculates the total revenue from customer orders by summing up all the order amounts. They discover that their algorithm is including refunded orders, which are recorded as negative amounts, and decide to refine the algorithm to ignore those. What structure must be added to the original algorithm to ignore the refunded orders?

Selection

A 5 year old visits the Computer History Museum and gets excited about everything computers can do. They ask their mother, "Mom, can computers solve every problem?" Which response is the most accurate?

There are some problems a computer can't solve, no matter how much time they have.

An online news website relies on in-page advertisements to make money. Their article pages have multiple slots for advertisements, and each slot can be used for a full-size ad or multiple smaller ads. Advertisers specify their size and desired display count per day. The news site uses a scheduling algorithm to determine which advertisements to display in each slot at each time of day. The algorithm's goal is to maximize money earned while not exceeding the display count per day, so it tries out every possible combination and picks the best one. As the number of advertisers and articles increases, the news site realizes the scheduling algorithm is taking an unreasonable amount of time and costing them valuable server time. What is the most promising way that they can improve the run time of the algorithm?

Use a heuristic-based algorithm that suggests an advertisement schedule that is close to optimal.

"Aba speak" is a game invented by school children to disguise what they're speaking. When speaking, they transform each word following this algorithm: For each letter in word: If letter is vowel: Add "b" after Add that letter after "b" Following that algorithm, how would they transform the word "avocado"?

abavobocabadobo

The goal of the procedure longestWord is to return the longest word in a given list of words. For example, if it's given the list ["superhero", "captain", "marvel"], it should return "superhero" as the longest word. PROCEDURE longestWord(words) { maxWordLen ← 0 maxWord ← "" FOR word IN words { IF (LENGTH(word) > maxWordLen) { maxWord ← word maxWordLen ← LENGTH(word) RETURN maxWord } } RETURN maxWord } A programmer tests the procedure with various inputs and finds that there are multiple cases where it does not produce the expected output. Which calls to longestWord() do not actually return the longest word? 👁️Note that there are 2 answers to this question.

longestWord(["frog", "seagull", "mermaid"]) longestWord(["crown", "diamond", "castle"])

The following algorithm displays a sequence of 10 odd squares: Start by setting n to 1. Repeat 10 times: Multiply n by itself and display the result. Add 2 to n. Which of these correctly expresses that algorithm in pseudocode?

n ← 1 REPEAT 10 TIMES { result ← n * n DISPLAY(result) n ← n + 2 }

A programmer for a weather website needs to display the proportion of days with freezing temperatures in a given month. Their algorithm will operate on a list of temperatures for each day in the month. It must keep track of how many temperatures are below or equal to 32. Once it's done processing the list, it must display the ratio of freezing days over total days. Which of these correctly expresses that algorithm in pseudocode?

numFreezing ← 0 numDays ← 0 FOR EACH temp IN temps { IF (temp ≤ 32) { numFreezing ← numFreezing + 1 } numDays ← numDays + 1 } DISPLAY(numFreezing/numDays)

The goal of the procedure reportErrors is to iterate through a list of strings and report how many of them contain disallowed characters ("!" and "&"). For example, if given the list ["ahoy", "mateys!", "fish&chips!"], it should return the number 2 since two of the three strings contain disallowed characters. PROCEDURE reportErrors(strings) { sumErrors ← 0 FOR str IN strings { IF (CONTAINS(str, "!") OR CONTAINS(str, "&")) { sumErrors ← sumErrors + 1 RETURN sumErrors } } RETURN sumErrors } A programmer tests the procedure with various inputs and finds multiple cases where it does not produce the expected output. Which calls to reportErrors() return an incorrect number of errors? 👁️Note that there are 2 answers to this question.

reportErrors(["computer-sc!ence", "html&css", "javascr1pt"]) reportErrors(["c@lculus", "prob&stats", "factorials!"])

Matching pennies is a game where players are awarded points based on whether their coins match. Here's an algorithm that simulates one round of the game: Randomly set coin1 to either "heads" or "tails" Randomly set coin2 to either "heads" or "tails" If coin1 matches coin2, increment score1 by 1 Otherwise, increment score2 by 1 Imagine that the algorithm is repeated three times to simulate three rounds of the game. This table shows the values for the coin variables in each round: round coin1 coin2 1 heads tails 2 heads heads 3 tails tails Assuming that score1 and score2 start at 0, what will be the values of score1 and score2 after the three rounds?

score1 will be 2 and score2 will be 1

The algorithm below determines whether a given year is a leap year. If year is not divisible by 4, set leap_year to false Else if year is not divisible by 100, set leap_year to true Else if year is not divisible by 400, set leap_year to false Else, set leap_year to true. Which of these tables correctly shows the results of this algorithm on the given values of year?

year leap_year 1900 false 1984 true 2000 true 2002 false


Set pelajaran terkait

AP Psych Incorrect/Hard Quiz Questions

View Set

PSY1010 CH11 Stress,Health,HumanFlorishingSummativeQuiz

View Set

CDC Volume 4 Bubble Sheet 1-90, CDC Volume 3 Unit 1-4 Bubble Sheet, CDC Volume 2 Unit 4, CDC Volume 2 Unit 3, CDC Volume 2 Unit 1, CDC Volume 2 Unit 2, CDCs Volume 1 Unit 5, CDCs Volume 1 Unit 4, CDCs Volume 1 Unit 3, CDCs Volume 1 Unit 2, CDC Volume...

View Set

Combo with "Geology Ch 2" and 27 others

View Set

Architecture Chapter 7, 8, and 9

View Set

Physical science Sandoy semester 1 final

View Set

Brown Astronomy Unit 2 Webassign Questions

View Set

The Definitive Anatomy EXAM 2 QUIZLET

View Set