Docsity

More Arrays and HashMaps - Section Handout - Programming Methodology- 34, Exercises of Programming Methodologies

Toggle sidebar
bg1
Mehran Sahami Handout #34
CS 106A November 5, 2007
Section Handout #6: More Arrays and HashMaps
Portions of this handout by Eric Roberts
1. Image processing (Chapter 11, exercise 12, page 458)
Write a method flipHorizontal that works similarly to the flipVertical method
presented in the chapter except that it reverses the 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:
2. Name Counts
Write a program that asks the user for a list of names (one per line) until the user enters a
blank line (i.e., just hits return when asked for a name). At that point the program should
print out how many times each name in the list was entered. You may find that using a
HashMap to keep track of the information entered by user may greatly simplify this
problem. A sample run of this program is shown below.
pf3

Partial preview of the text

Download More Arrays and HashMaps - Section Handout - Programming Methodology- 34 and more Exercises Programming Methodologies in PDF only on Docsity!

Mehran Sahami Handout

CS 106A November 5, 2007

Section Handout #6: More Arrays and HashMaps

Portions of this handout by Eric Roberts

1. Image processing (Chapter 11, exercise 12, page 458)

Write a method flipHorizontal that works similarly to the flipVertical method

presented in the chapter except that it reverses the 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:

2. Name Counts

Write a program that asks the user for a list of names (one per line) until the user enters a

blank line (i.e., just hits return when asked for a name). At that point the program should

print out how many times each name in the list was entered. You may find that using a

HashMap to keep track of the information entered by user may greatly simplify this

problem. A sample run of this program is shown below.

Mehran Sahami Handout #34A

CS 106A November 7, 2007

Solutions to Section

1. Image processing

private GImage flipHorizontal(GImage image) { int[][] array = image.getPixelArray(); int width = array[0].length; int height = array.length; for (int row = 0; row < height; row++) { for (int p1 = 0; p1 < width / 2; p1++) { int p2 = width - p1 - 1; int temp = array[row][p1]; array[row][p1] = array[row][p2]; array[row][p2] = temp; } } return new GImage(array); }

Solution for Problem #2 Name Counts on back of page.