From 120d6f860dfa48e61c53dc4c4b9442e043b5b80d Mon Sep 17 00:00:00 2001 From: NunoSempere Date: Sat, 13 Apr 2024 12:35:52 -0400 Subject: [PATCH] add reading a specific election --- main.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index c316ef1..92138d2 100644 --- a/main.go +++ b/main.go @@ -62,19 +62,78 @@ func findElectoralVotes(stateVotes []StateVotes, stateName string) (int, error) /* 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() { - // Get electoral votes - filename := "data/electoral-college-votes.csv" - stateVotes, err := readElectoralVotes(filename) + filename := "data/2000.csv" // Update with the actual filename + results, err := readElectionResults(filename) if err != nil { fmt.Println("Error:", err) return } - // Get baserates - // Example states to query 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 { votes, err := findElectoralVotes(stateVotes, state) if err != nil { @@ -83,4 +142,5 @@ func main() { fmt.Printf("%s has %d electoral votes.\n", state, votes) } } + }