-
-
Save Zazucki/340f7691c3afa0b2e58112619c4f1afb to your computer and use it in GitHub Desktop.
Go Simulation of the Monty Hall Problem for N-Doors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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