-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathATL_Votes_052021.go
50 lines (36 loc) · 1.37 KB
/
ATL_Votes_052021.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Arrays.asList("A", "B", "A", "C", "D", "B", "A");
String findWinner(List<String> votes)
Given a list of strings containing votes cast for a set of candidates, find the winning candidate.
The votes data structure consists of candidate names represented as strings (for simplicity, consider candidate names
to be case-sensitive. i.e. "A" and "a" would be two distinct candaidate names.).
P.S: how could ties be handled?
*/
package main
import (
"log"
)
func main() {
// log.Printf("%s\n", findWinner([]string{"A", "B", "A", "C", "D", "B", "A"}))
tests := [][]string{{"A", "B", "A", "C", "D", "B", "A"}, {"A"}, {"A", "B"}, {"B", "A", "B"}}
for _, test := range tests {
log.Printf("findWinner(%s) = %s\n", test, findWinner(test))
}
}
// findWinner accepts a slice of strings consisting cast votes, and returns the winning candidate name.
func findWinner(votes []string) string {
// declare map mapping each candidate name to the number of votes they received
candidateVotes := map[string]int{}
// iterate through the votes slice and update candidate/vote map
// keep track of the candidate with most votes (count and name)
var winnerVotes int
var winnerName string
for _, candidate := range votes {
candidateVotes[candidate]++
if candidateVotes[candidate] > winnerVotes {
winnerVotes = candidateVotes[candidate]
winnerName = candidate
}
}
return winnerName
}