Skip to content

Instantly share code, notes, and snippets.

@zzstoatzz
Created March 17, 2024 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzstoatzz/623be3974cca9de7d5f63a9f412bc50a to your computer and use it in GitHub Desktop.
Save zzstoatzz/623be3974cca9de7d5f63a9f412bc50a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"sync"
"gonum.org/v1/gonum/stat"
)
func main() {
simulations := 1000000
flips := 100
var wg sync.WaitGroup
resultsChan := make(chan []int, simulations)
for i := 0; i < simulations; i++ {
wg.Add(1)
go func() {
defer wg.Done()
alice, bob := runSimulation(flips)
resultsChan <- []int{alice, bob}
}()
}
wg.Wait()
close(resultsChan)
var aliceWins, bobWins, ties int
var alicePoints, bobPoints []float64
for result := range resultsChan {
alice, bob := result[0], result[1]
alicePoints = append(alicePoints, float64(alice))
bobPoints = append(bobPoints, float64(bob))
if alice > bob {
aliceWins++
} else if bob > alice {
bobWins++
} else {
ties++
}
}
fmt.Printf("Simulations: %d\n", simulations)
fmt.Printf("Alice wins: %d\n", aliceWins)
fmt.Printf("Bob wins: %d\n", bobWins)
fmt.Printf("Ties: %d\n", ties)
fmt.Printf("Alice's average points: %.2f\n", stat.Mean(alicePoints, nil))
fmt.Printf("Bob's average points: %.2f\n", stat.Mean(bobPoints, nil))
fmt.Printf("Alice's standard deviation: %.2f\n", stat.StdDev(alicePoints, nil))
fmt.Printf("Bob's standard deviation: %.2f\n", stat.StdDev(bobPoints, nil))
}
func runSimulation(flips int) (int, int) {
alice := 0
bob := 0
prev := ""
for i := 0; i < flips; i++ {
flip := "H"
if rand.Float64() < 0.5 {
flip = "T"
}
if prev == "H" {
if flip == "T" {
bob++
} else {
alice++
}
}
prev = flip
}
return alice, bob
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment