From a4095d77d237902ee46f90bf517ea47f9f3f8ad5 Mon Sep 17 00:00:00 2001 From: Jesper Handskemager Date: Thu, 23 Feb 2023 12:58:32 +0100 Subject: [PATCH] Initial commit --- go.mod | 3 +++ main.go | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a67db7e --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module MontyHallStats + +go 1.20 diff --git a/main.go b/main.go new file mode 100644 index 0000000..b173ab1 --- /dev/null +++ b/main.go @@ -0,0 +1,80 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func play_game(switchDoor bool) bool { + // Initialize the random number generator with the current time + rng := rand.New(rand.NewSource(time.Now().UnixNano())) + + doors := []int{1, 2, 3} + prize := doors[rng.Intn(3)] + chosen := 0 + + // Create a new source of random + rng = rand.New(rand.NewSource(time.Now().UnixNano())) + + // Select a random door + input := rng.Intn(3) + chosen = input + + // Open one of the other two doors to reveal a goat + var opened int + for _, door := range doors { + if door != chosen && door != prize { + opened = door + break + } + } + + // Switch the door if switchDoor equals true + if switchDoor { + for _, door := range doors { + if door != chosen && door != opened { + chosen = door + break + } + } + } + + // Return if the prize is won + return chosen == prize +} + +func main() { + // How many games to play + gamesToPlay := 10000 + games := make([]int, gamesToPlay) + + // Should the door be switched? + switchDoor := true + + for i := 0; i < gamesToPlay; i++ { + won := play_game(switchDoor) + if won { + games[i] = 1 + } else { + games[i] = 0 + } + } + + totalWon := 0 + totalLost := 0 + + // Count the number of won and lost games + for _, num := range games { + if num == 0 { + totalLost++ + } else { + totalWon++ + } + } + + // Calculate the winning chance + winningChance := float64(totalWon) / float64(gamesToPlay) * 100.0 + fmt.Printf("In %d games\nGames won: %d\nGames Lost: %d\n", gamesToPlay, totalWon, totalLost) + fmt.Printf("This gives you a winning chance of %.2f%% percent\n", winningChance) +}