35-section-6

35-section-6 - Mehran Sahami CS 106A Handout #35 November...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Mehran Sahami CS 106A Handout #35 November 7, 2011 Section Handout #6: More Arrays and HashMaps Portions of this handout by Eric Roberts 1. How Prime! In the third century B.C., the Greek astronomer Eratosthenes developed an algorithm for finding all the prime numbers up to some upper limit N. To apply the algorithm, you start by writing down a list of the integers between 2 and N. For example, if N were 20, you would begin by writing down the following list: You then begin by circling the first number in the list, indicating that you have found a prime. You then go through the rest of the list and cross off every multiple of the value you have just circled, since none of those multiples can be prime. Thus, after executing the first step of the algorithm, you will have circled the number 2 and crossed off every multiple of two, as follows: From here, you simply repeat the process by circling the first number in the list that is neither crossed off nor circled, and then crossing off its multiples. Eventually, every number in the list will either be circled or crossed out, as shown in this diagram: The circled numbers are the primes; the crossed-out numbers are composites. This algorithm for generating a list of primes is called the sieve of Eratosthenes. Write a program that uses the sieve of Eratosthenes to generate a list of all prime numbers between 2 and 1000. Courtesy: xkcd.com 2. Image processing (Chapter 11, exercise 12, page 458) Write a method flipHorizontal that reverses a picture in the horizontal dimension. Thus, if you had a GImage containing the image on the left (of Jan Vermeer’s The Milkmaid, c. 1659), calling flipHorizontal on that image would return a new GImage as shown on the right: → 3. Word Frequency Write a program that asks the user to input a file name, and then reads the file and prints out how many times each word appeared. You may find that using a HashMap to keep track of this information will simplify the problem. An example run below: To improve your program, try only keeping words with a certain minimum length, and only print out words with a certain minimum count. If you have time, see if you can print the most frequent word. ...
View Full Document

Ask a homework question - tutors are online