added votes to learn maps

This commit is contained in:
John O'Keefe 2023-12-20 11:41:47 -05:00
parent 8c5dd62355
commit 6bcbe63df5

View File

@ -5,6 +5,7 @@ import (
"fmt"
"git.linuxhg.com/john-okeefe/datafile"
"git.linuxhg.com/john-okeefe/keyboard"
"sort"
"strings"
)
@ -15,5 +16,41 @@ func countVotes() {
fileString = strings.TrimSpace(fileString)
lines, err := datafile.GetStrings(fileString)
Error(err)
fmt.Println(lines)
// 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])
}
}