Skip to content

Instantly share code, notes, and snippets.

@Zazucki
Forked from ryansturmer/montyhall.py
Last active February 14, 2024 21:14
Show Gist options
  • Save Zazucki/340f7691c3afa0b2e58112619c4f1afb to your computer and use it in GitHub Desktop.
Save Zazucki/340f7691c3afa0b2e58112619c4f1afb to your computer and use it in GitHub Desktop.
Go Simulation of the Monty Hall Problem for N-Doors
// Monty Hall Problem Simulation
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 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
}
}
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)))
}
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