add reading a specific election

This commit is contained in:
NunoSempere 2024-04-13 12:35:52 -04:00
parent b918a94e8b
commit 120d6f860d

70
main.go
View File

@ -62,19 +62,78 @@ func findElectoralVotes(stateVotes []StateVotes, stateName string) (int, error)
/* Results for the elections */ /* Results for the elections */
type StateResult struct {
State string
Party string
}
func readElectionResults(filename string) ([]StateResult, error) {
var results []StateResult
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("error opening the file: %v", err)
}
defer file.Close()
reader := csv.NewReader(file)
// Skip the header
if _, err := reader.Read(); err != nil {
return nil, fmt.Errorf("error reading header row: %v", err)
}
for {
record, err := reader.Read()
if err != nil {
break // End of file or an error
}
results = append(results, StateResult{State: record[0], Party: record[1]})
}
if len(results) == 0 {
return nil, fmt.Errorf("no data found")
}
return results, nil
}
// findWinningParty searches the provided slice of StateResults for a given state and returns its winning party.
func findWinningParty(results []StateResult, stateName string) (string, error) {
for _, result := range results {
if strings.EqualFold(result.State, stateName) {
return result.Party, nil
}
}
// If the loop completes without finding the state, it's not in the list.
return "", fmt.Errorf("state not found")
}
func main() { func main() {
// Get electoral votes filename := "data/2000.csv" // Update with the actual filename
filename := "data/electoral-college-votes.csv" results, err := readElectionResults(filename)
stateVotes, err := readElectoralVotes(filename)
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
return return
} }
// Get baserates
// Example states to query // Example states to query
states := []string{"California", "Texas", "Florida"} states := []string{"California", "Texas", "Florida"}
for _, state := range states {
party, err := findWinningParty(results, state)
if err != nil {
fmt.Printf("Error: %s\n", err)
} else {
fmt.Printf("%s won by %s in 2000 US election.\n", state, party)
}
}
filename = "data/electoral-college-votes.csv"
stateVotes, err := readElectoralVotes(filename)
if err != nil {
fmt.Println("Error:", err)
return
}
for _, state := range states { for _, state := range states {
votes, err := findElectoralVotes(stateVotes, state) votes, err := findElectoralVotes(stateVotes, state)
if err != nil { if err != nil {
@ -83,4 +142,5 @@ func main() {
fmt.Printf("%s has %d electoral votes.\n", state, votes) fmt.Printf("%s has %d electoral votes.\n", state, votes)
} }
} }
} }