Chapter 7 - Maps

Exercise 2: Sorting Map Keys

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.

Solution

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.
	var names []string
	for name := range counts {
		names = append(names, name)
	}
	// Call the sort.Strings method on your slice.
	sort.Strings(names)
	// Loop through the names in the sorted slice, and
	// print the name and the corresponding count from
	// the map.
	for _, name := range names {
		fmt.Printf("Votes for %s: %d\n", name, counts[name])
	}
}

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