add results histogram

This commit is contained in:
NunoSempere 2024-04-14 15:33:36 -04:00
parent 0405e3815c
commit 9dcc442584

38
main.go
View File

@ -373,6 +373,7 @@ func sampleFromState(state State) VotesForEachParty {
} }
} }
/* Simulate election */
func simulateElection(states []State) int { func simulateElection(states []State) int {
republican_seats := 0 republican_seats := 0
@ -383,6 +384,36 @@ func simulateElection(states []State) int {
return republican_seats return republican_seats
} }
/* Histogram */
func barString(n int) string {
str := ""
for i := 0; i < n; i++ {
str += "█"
}
return str
}
func printElectoralCollegeHistogram(samples []int) {
histogram := [538]int{}
for _, sample := range samples {
histogram[sample]++
}
max_count := 0
for _, count := range histogram {
if count > max_count {
max_count = count
}
}
for i, count := range histogram {
bar_length := (count * 100) / max_count // Assuming max_count bar length is 50 characters
fmt.Printf("[ %2d, %4d): %s %d\n", i, i+1, barString(bar_length), count)
}
}
func main() { func main() {
states, err := readStates() states, err := readStates()
if err != nil { if err != nil {
@ -390,19 +421,22 @@ func main() {
return return
} }
n_sims := 10_000 n_sims := 100_000
printStates(states) printStates(states)
p_republicans := 0.0 p_republicans := 0.0
results := make([]int, n_sims)
for i := 0; i < n_sims; i++ { for i := 0; i < n_sims; i++ {
republican_seats := simulateElection(states) republican_seats := simulateElection(states)
results[i] = republican_seats
if republican_seats >= 270 { if republican_seats >= 270 {
p_republicans++ p_republicans++
} }
fmt.Printf("%d - %t\n", republican_seats, republican_seats >= 270) // fmt.Printf("%d - %t\n", republican_seats, republican_seats >= 270)
} }
p_republicans = p_republicans / float64(n_sims) p_republicans = p_republicans / float64(n_sims)
fmt.Printf("\n\n\n%% republicans: %f\n", p_republicans) fmt.Printf("\n\n\n%% republicans: %f\n", p_republicans)
printElectoralCollegeHistogram(results)
} }