From 6bcbe63df5a54573a4b222970e7fda2efae88079 Mon Sep 17 00:00:00 2001 From: John O'Keefe Date: Wed, 20 Dec 2023 11:41:47 -0500 Subject: [PATCH] added votes to learn maps --- playground/countVotes.go | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/playground/countVotes.go b/playground/countVotes.go index 7148dbf..fa840d1 100644 --- a/playground/countVotes.go +++ b/playground/countVotes.go @@ -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]) + } }