use array for election results instead of individual year

This commit is contained in:
NunoSempere 2024-04-13 15:07:29 -04:00
parent 08571ee9b6
commit 18cb3710d9

49
main.go
View File

@ -11,17 +11,11 @@ import (
type State struct {
Name string
Votes int
Party2000 string
Party2004 string
Party2008 string
Party2012 string
Party2016 string
Party2020 string
VictoriousPartyPerElection map[string]string
}
func readStates() ([]State, error) {
var states map[string]State = make(map[string]State)
var years = []string{"2000", "2004", "2008", "2012", "2016", "2020"}
/* Electoral college votes for the 2024 election*/
votes_file, err := os.Open("data/electoral-college-votes.csv")
@ -45,11 +39,12 @@ func readStates() ([]State, error) {
}
state := csv_record[0]
if _, exists := states[state]; !exists {
states[state] = State{Name: state, Votes: votes}
states[state] = State{Name: state, Votes: votes, VictoriousPartyPerElection: make(map[string]string)}
}
}
/* Election results */
var years = []string{"2000", "2004", "2008", "2012", "2016", "2020"}
for _, year := range years {
results_filename := fmt.Sprintf("data/results/%s.csv", year)
results_file, err := os.Open(results_filename)
@ -72,31 +67,18 @@ func readStates() ([]State, error) {
continue // State not found in votes map, skip
}
// Update the party winning in the specific year
switch year {
case "2000":
data.Party2000 = party
case "2004":
data.Party2004 = party
case "2008":
data.Party2008 = party
case "2012":
data.Party2012 = party
case "2016":
data.Party2016 = party
case "2020":
data.Party2020 = party
}
data.VictoriousPartyPerElection[year] = party
states[state] = data
}
}
// Convert statesData map to a slice for returning
var dataSlice []State
for _, data := range states {
dataSlice = append(dataSlice, data)
var states_slice []State
for _, state := range states {
states_slice = append(states_slice, state)
}
return dataSlice, nil
return states_slice, nil
}
type VotesForEachParty struct {
@ -124,15 +106,18 @@ func main() {
// Example states to query
example_state_names := []string{"California", "Texas", "Florida"}
for _, states := range states {
for _, state := range states {
for _, example_state_name := range example_state_names {
if strings.EqualFold(states.Name, example_state_name) {
fmt.Printf("%s: Votes: %d, Winners: 2000 - %s, 2004 - %s, 2008 - %s, 2012 - %s, 2016 - %s, 2020 - %s\n",
states.Name, states.Votes,
states.Party2000, states.Party2004, states.Party2008,
states.Party2012, states.Party2016, states.Party2020)
if strings.EqualFold(state.Name, example_state_name) {
fmt.Printf("%s: Votes: %d, Winners: ", state.Name, state.Votes)
for year, party := range state.VictoriousPartyPerElection {
fmt.Printf("[%s: %s] ", year, party)
}
fmt.Println()
break
}
}
}
}