Skip to content

Instantly share code, notes, and snippets.

@monkeyworknet
Last active July 5, 2018 02:18
Show Gist options
  • Save monkeyworknet/78c04b6763ba83cfc50c2441302cb3d3 to your computer and use it in GitHub Desktop.
Save monkeyworknet/78c04b6763ba83cfc50c2441302cb3d3 to your computer and use it in GitHub Desktop.
Monty Hall Problem
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var Swappers int
var Stayers int
func main() {
// create a work group
// set # of itterations
var wg sync.WaitGroup
simulations := 100000
wg.Add(simulations)
now := time.Now()
for i := 0; i < simulations/2; i++ {
go sim(true, &wg)
go sim(false, &wg)
}
wg.Wait()
x := PercentOf(Swappers, simulations/2)
y := PercentOf(Stayers, simulations/2)
timesince := time.Since(now).Seconds()
fmt.Println("Running Threaded")
fmt.Printf("Ran %v Simulations. Took %.2v seconds\n", simulations, timesince)
fmt.Printf("Those who swapped doors won %v percent of the time while those who did not only won %v percent\n", x, y)
now = time.Now()
wg.Add(simulations)
Swappers, Stayers, x, y = 0, 0, 0, 0
for i := 0; i < simulations/2; i++ {
sim(true, &wg)
sim(false, &wg)
}
wg.Wait()
x = PercentOf(Swappers, simulations/2)
y = PercentOf(Stayers, simulations/2)
timesince = time.Since(now).Seconds()
fmt.Println("Running Serial")
fmt.Printf("Ran %v Simulations. Took %.2v seconds\n", simulations, timesince)
fmt.Printf("Those who swapped doors won %v percent of the time while those who did not only won %v percent\n", x, y)
}
// takes in s as a bool to determin if swapping doors
func sim(s bool, wg *sync.WaitGroup) {
// close the Worker Group at end of execution
defer wg.Done()
// seed math/rand - deterministic result based on known seed but not important for this exercise.
rand.Seed(time.Now().UTC().UnixNano())
// randomly select which door is the winner
winner := rand.Intn(3)
doors := []int{0, 0, 0}
doors[winner] = 1
// randomly select which door the player picked
selected := rand.Intn(3)
// now assume we have eliminated a non-winning door, leaving only the winning door and a losing door - one of which has been selected by the player
if s == true {
// if we swap doors and our initially selected door was a loser than we return a winning 1
if doors[selected] == 0 {
Swappers = Swappers + 1
// fmt.Println("winner")
return
}
// fmt.Println("loser")
return
}
if doors[selected] == 0 {
// if we did not swap and the player did not select the winner then they lose.
// fmt.Println("loser")
return
}
Stayers = Stayers + 1
//fmt.Println("winner")
return
}
func PercentOf(current int, all int) float64 {
percent := (float64(current) * float64(100)) / float64(all)
return percent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment