trying_out_go/cmd/playground/countVotes.go

57 lines
1.0 KiB
Go

// from Chapter 7 of Head First Go
package main
import (
"fmt"
"sort"
"strings"
"trying_out_go/pkg/datafile"
"trying_out_go/pkg/keyboard"
)
func countVotes() {
fmt.Printf("What is the name of the file: ")
fileString, err := keyboard.GetString()
Error(err)
fileString = strings.TrimSpace(fileString)
lines, err := datafile.GetStrings(fileString)
Error(err)
// Count the hard way with slices
var names []string
var counts []int
for _, line := range lines {
matched := false
for i, name := range names {
if name == line {
counts[i]++
matched = true
}
}
if matched == false {
names = append(names, line)
counts = append(counts, 1)
}
}
for i, name := range names {
fmt.Printf("%s: %d\n", name, counts[i])
}
fmt.Println("")
// Easy way
votes := make(map[string]int)
var namesMap []string
for _, line := range lines {
votes[line]++
}
for name := range votes {
namesMap = append(namesMap, name)
}
sort.Strings(namesMap)
for _, name := range namesMap {
fmt.Printf("%v: %v\n", name, votes[name])
}
}