Chapter 7 - Maps
Exercise 1: Counting Occurrences of Strings
In the chapter 5 exercises, we asked you to count how many times the numbers 0, 1, and 2 occurred within an array. This time, your task is to count how many times letters occur within a slice.
Hint: You can set up a map with strings as its keys and integers as its values. The values can be used to keep track of the number of times each key string has occurred.
Solution
Here’s our solution.
Exercise 2: Sorting Map Contents
Here’s a new votes.txt
file. It’s been updated to list candidate names in “last name, first name” order, and there are several more candidate names now.
Wilkins, Dennis
Rodriquez, Jamie
Hines, Domingo
Wolfe, Kelly
Carr, Darla
Rodriquez, Jamie
Wolfe, Kelly
Wilkins, Dennis
Carr, Darla
Rodriquez, Jamie
Hines, Domingo
Our vote counting program still works with this updated file, but we’re really starting to wish the results were easier to read. Update the program to print the candidates in alphabetical order by name. You can use the sort
package’s Strings
method to sort the candidate names.
Output:
Votes for Carr, Darla: 2
Votes for Hines, Domingo: 2
Votes for Rodriquez, Jamie: 3
Votes for Wilkins, Dennis: 2
Votes for Wolfe, Kelly: 2
Here’s our solution.