34a section 6 solutions


Mehran Sahami Handout #34A
CS 106A November 7, 2007
Solutions to Section #6
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.
 2 
2. Name Counts
/*
* File: CountNames.java
* ---------------------
* This program shows an example of using a HashMap. It reads a
* list of names from the user and list out how many times each name
* appeared in the list.
*/
import acm.program.*;
import java.util.*;
public class CountNames extends ConsoleProgram {
public void run() {
HashMap nameMap = new HashMap();
readNames(nameMap);
printMap(nameMap);
}
/*
* Reads a list of names from the user, storing names and how many
* times each appeared in the map that is passed in as a parameter.
*/
private void readNames(Map map) {
while (true) {
String name = readLine("Enter name: ");
if (name.equals("")) break;
// See if that name previously appeared in the map. Update
// count if it did, or create a new count if it didn't.
Integer count = map.get(name);
if (count == null) {
count = new Integer(1);
} else {
count = new Integer(count + 1);
}
map.put(name, count);
}
}
/*
* Prints out list of entries (and associated counts) from the map
* that is passed in as a parameter.
*/
private void printMap(Map map) {
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
int count = map.get(key);
println("Entry [" + key + "] has count " + count);
}
}
}


Wyszukiwarka