2024-04-13 14:22:28 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-04-13 15:10:50 +00:00
|
|
|
"encoding/csv"
|
2024-04-13 14:22:28 +00:00
|
|
|
"fmt"
|
2024-04-13 15:10:50 +00:00
|
|
|
"os"
|
|
|
|
"strings"
|
2024-04-13 14:22:28 +00:00
|
|
|
)
|
|
|
|
|
2024-04-13 15:10:50 +00:00
|
|
|
/* Electoral votes */
|
|
|
|
type StateVotes struct {
|
|
|
|
State string
|
|
|
|
Votes string
|
|
|
|
}
|
|
|
|
|
|
|
|
func readElectoralVotes(filename string) ([]StateVotes, error) {
|
|
|
|
file, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error opening the file: %v", err)
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
var stateVotes []StateVotes
|
|
|
|
|
|
|
|
reader := csv.NewReader(file)
|
|
|
|
for {
|
|
|
|
record, err := reader.Read()
|
|
|
|
// End of file is expected, not an error in this context
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
stateVotes = append(stateVotes, StateVotes{State: record[0], Votes: record[1]})
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(stateVotes) == 0 {
|
|
|
|
return nil, fmt.Errorf("no data found")
|
|
|
|
}
|
|
|
|
|
|
|
|
return stateVotes, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func findElectoralVotes(stateVotes []StateVotes, stateName string) (string, error) {
|
|
|
|
for _, sv := range stateVotes {
|
|
|
|
if strings.EqualFold(sv.State, stateName) {
|
|
|
|
return sv.Votes, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", fmt.Errorf("state not found")
|
|
|
|
}
|
|
|
|
|
2024-04-13 14:22:28 +00:00
|
|
|
func main() {
|
2024-04-13 15:10:50 +00:00
|
|
|
filename := "data/electoral-college-votes.csv"
|
|
|
|
stateVotes, err := readElectoralVotes(filename)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("Error:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Example states to query
|
|
|
|
states := []string{"California", "Texas", "Florida"}
|
|
|
|
for _, state := range states {
|
|
|
|
votes, err := findElectoralVotes(stateVotes, state)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Error: %s\n", err)
|
|
|
|
} else {
|
|
|
|
fmt.Printf("%s has %s electoral votes.\n", state, votes)
|
|
|
|
}
|
|
|
|
}
|
2024-04-13 14:22:28 +00:00
|
|
|
}
|