add simulate election function; consider Maine and Nebraska separately

This commit is contained in:
NunoSempere 2024-04-13 15:52:39 -04:00
parent d1dc3a5e75
commit 9ca60febac
2 changed files with 64 additions and 11 deletions

3
data/results/src.txt Normal file
View File

@ -0,0 +1,3 @@
https://www.archives.gov/electoral-college/2020
https://www.archives.gov/electoral-college/[year]

72
main.go
View File

@ -21,7 +21,7 @@ type VotesForEachParty struct {
Republicans int
}
type src = *rand.Rand
// type src = *rand.Rand
/* Globals */
var r = rand.New(rand.NewPCG(uint64(1), uint64(2)))
@ -97,9 +97,31 @@ func readStates() ([]State, error) {
func sampleFromState(state State) VotesForEachParty {
switch state.Name {
case "Nebraska":
return VotesForEachParty{Democrats: 1, Republicans: 0}
// 2000: R
// 2004: R
// 2008: Split, 1 D, 4 R
// 2012: R
// 2016: R
// 2020: Split, 1 D, 4 R
p_split := float64(2 / 6)
if r.Float64() < p_split {
return VotesForEachParty{Democrats: 1, Republicans: 4}
} else {
return VotesForEachParty{Democrats: 0, Republicans: 5}
}
case "Maine":
// 2000: D
// 2004: D
// 2008: D
// 2012: D
// 2016: Split: 3 D, 1 R
// 2020: Split, 3 D, 1 R
p_split := float64(2 / 6)
if r.Float64() < p_split {
return VotesForEachParty{Democrats: 3, Republicans: 1}
} else {
return VotesForEachParty{Democrats: 1, Republicans: 0}
}
default:
{
p_republican := 0.0
@ -118,6 +140,32 @@ func sampleFromState(state State) VotesForEachParty {
}
}
func simulateElection(states []State) int {
republican_seats := 0
for _, state := range states {
election_sample := sampleFromState(state)
republican_seats += election_sample.Republicans
/*
fmt.Printf("%s: Votes: %d,\n\tWinners: ", state.Name, state.Votes)
for year, party := range state.VictoriousPartyPerElection {
fmt.Printf("[%s: %s] ", year, party)
}
fmt.Printf("\n\tSample: Democrat seats: %d, Republican seats: %d", election_sample.Democrats, election_sample.Republicans)
fmt.Println()
*/
}
// fmt.Printf("\nDemocrat seats: %d\n", republican_seats)
if republican_seats > 270 {
return 1
} else {
return 0
}
}
func main() {
states, err := readStates()
if err != nil {
@ -125,15 +173,17 @@ func main() {
return
}
for _, state := range states {
fmt.Printf("%s: Votes: %d,\n\tWinners: ", state.Name, state.Votes)
for year, party := range state.VictoriousPartyPerElection {
fmt.Printf("[%s: %s] ", year, party)
}
election_sample := sampleFromState(state)
fmt.Printf("\n\tSample: Democrat seats: %d, Republican seats: %d", election_sample.Democrats, election_sample.Republicans)
fmt.Println()
n_sims := 100_000
p_republicans := 0.0
for _ = range n_sims {
result := simulateElection(states)
fmt.Printf("Election result: %d\n", result)
if result == 1 {
p_republicans++
}
}
p_republicans = p_republicans / float64(n_sims)
fmt.Printf("%% republicans: %f\n", p_republicans)
}