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
package main
import "fmt"
func main() {
// We'll count the number of times each letter occurs
// within this slice.
letters := []string{"b", "a", "c", "a", "b", "a",
"a", "b", "c"}
// YOUR CODE HERE: Process each element of "letters",
// keeping track of how many times you've seen "a",
// "b", or "c".
// Finally, print out the number of times each letter
// occurred.
}
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.
package main
import (
"fmt"
"log"
"sort"
"github.com/headfirstgo/datafile"
)
func main() {
lines, err := datafile.GetStrings("votes.txt")
if err != nil {
log.Fatal(err)
}
counts := make(map[string]int)
for _, line := range lines {
counts[line]++
}
// YOUR CODE HERE: Build a slice containing all the
// key strings from the "counts" map.
// Call the sort.Strings method on your slice.
// Loop through the names in the sorted slice, and
// print the name and the corresponding count from
// the map.
}
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.