Skip to content

Instantly share code, notes, and snippets.

@Zazucki
Forked from ryansturmer/monty2.py
Last active February 14, 2024 21:38
Show Gist options
  • Save Zazucki/cd2907a6acf098f427653a85b8c5876f to your computer and use it in GitHub Desktop.
Save Zazucki/cd2907a6acf098f427653a85b8c5876f to your computer and use it in GitHub Desktop.
Monty Hall Problem
// Monty Hall Problem Simulation (updated)
package main
import (
"fmt"
"math/rand"
"time"
)
func play_round(doors int, trade bool) bool {
var car int
var initial_choice int
var monty_leaves int
var final_choice int
var victory bool
// Choose the location of the car
car = rand.Intn(doors)
// Contestant chooses a door
initial_choice = rand.Intn(doors)
// Monty opens ALL the other doors except one
if initial_choice != car {
monty_leaves = car // If the car wasn't chosen, Monty is forced to reveal its location
} else {
for {
monty_leaves = rand.Intn(doors)
if monty_leaves != initial_choice {
break
}
}
}
// monty_leaves is now the door that Monty DIDN'T open
if trade {
final_choice = monty_leaves
} else {
final_choice = initial_choice
}
victory = (final_choice == car)
return victory
}
func simulation(iterations int, doors int) {
var games_won_trade, games_won_notrade, games_won_random int
var victory bool
var i int = 1
for i <= iterations {
victory = play_round(doors, false)
if victory {
games_won_notrade += 1
i += 1
}
victory = play_round(doors, true)
if victory {
games_won_trade += 1
i += 1
}
victory = play_round(doors, (rand.Intn(2) == 0))
if victory {
games_won_random += 1
i += 1
}
}
fmt.Println("")
fmt.Println(" Monty Hall Simulation")
fmt.Println("----------------------------------------------------------")
fmt.Println(" Iterations:", iterations)
fmt.Printf("\n Games won when switching doors: %d (%f%%)", (games_won_trade), (100 * float32(games_won_trade) / float32(iterations)))
fmt.Printf("\n Games won when NOT switching doors: %d (%f%%)", (games_won_notrade), (100 * float32(games_won_notrade) / float32(iterations)))
fmt.Printf("\nGames won when random switching doors: %d (%f%%)\n\n", (games_won_random), (100 * float32(games_won_random) / float32(iterations)))}
func main() {
var iterations int = 1000000
var doors int = 3
rand.Seed(time.Now().UnixNano())
simulation(iterations, doors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment