change votes to int
This commit is contained in:
parent
3622b3ea3e
commit
b918a94e8b
30
main.go
30
main.go
|
@ -4,32 +4,43 @@ import (
|
|||
"encoding/csv"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
/* Electoral votes */
|
||||
type StateVotes struct {
|
||||
State string
|
||||
Votes string
|
||||
Votes int
|
||||
}
|
||||
|
||||
func readElectoralVotes(filename string) ([]StateVotes, error) {
|
||||
var stateVotes []StateVotes
|
||||
|
||||
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)
|
||||
// Skip the first row ('State, Votes' header)
|
||||
if _, err := reader.Read(); err != nil {
|
||||
return nil, fmt.Errorf("error reading header row: %v", err)
|
||||
}
|
||||
|
||||
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]})
|
||||
|
||||
votes, err := strconv.Atoi(record[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error converting votes for %s to int: %v", record[0], err)
|
||||
}
|
||||
stateVotes = append(stateVotes, StateVotes{State: record[0], Votes: votes})
|
||||
}
|
||||
|
||||
if len(stateVotes) == 0 {
|
||||
|
@ -39,17 +50,20 @@ func readElectoralVotes(filename string) ([]StateVotes, error) {
|
|||
return stateVotes, nil
|
||||
}
|
||||
|
||||
func findElectoralVotes(stateVotes []StateVotes, stateName string) (string, error) {
|
||||
func findElectoralVotes(stateVotes []StateVotes, stateName string) (int, error) {
|
||||
for _, sv := range stateVotes {
|
||||
if strings.EqualFold(sv.State, stateName) {
|
||||
return sv.Votes, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("state not found")
|
||||
return 0, fmt.Errorf("state not found")
|
||||
}
|
||||
|
||||
/* Results for the elections */
|
||||
|
||||
func main() {
|
||||
// Get electoral votes
|
||||
filename := "data/electoral-college-votes.csv"
|
||||
stateVotes, err := readElectoralVotes(filename)
|
||||
if err != nil {
|
||||
|
@ -57,6 +71,8 @@ func main() {
|
|||
return
|
||||
}
|
||||
|
||||
// Get baserates
|
||||
|
||||
// Example states to query
|
||||
states := []string{"California", "Texas", "Florida"}
|
||||
for _, state := range states {
|
||||
|
@ -64,7 +80,7 @@ func main() {
|
|||
if err != nil {
|
||||
fmt.Printf("Error: %s\n", err)
|
||||
} else {
|
||||
fmt.Printf("%s has %s electoral votes.\n", state, votes)
|
||||
fmt.Printf("%s has %d electoral votes.\n", state, votes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user