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".
	// "occurrences" will have the keys "a", "b", and "c".
	// The values will be the number of times that letter
	// has occurred.
	occurrences := make(map[string]int)
	// Process each element in "letters". We ignore the
	// index because we don't need it.
	for _, letter := range letters {
		// The zero value for values in "occurrences"
		// is 0. So we can safely increment it even if
		// we've never assigned to it.
		occurrences[letter]++
	}
	// Finally, print out the number of times each letter
	// occurred.
	for letter, count := range occurrences {
		fmt.Println(letter, "occurred", count, "times")
	}
}