trying_out_go/playground/countVotes.go

57 lines
1.1 KiB
Go
Raw Normal View History

2023-12-19 09:24:56 -05:00
// from Chapter 7 of Head First Go
package main
import (
"fmt"
"git.linuxhg.com/john-okeefe/datafile"
"git.linuxhg.com/john-okeefe/keyboard"
2023-12-20 11:41:47 -05:00
"sort"
2023-12-19 09:24:56 -05:00
"strings"
)
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)
2023-12-20 11:41:47 -05:00
// 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])
}
2023-12-19 09:24:56 -05:00
}