This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -1,63 +1,27 @@
package main
import (
"fmt"
"math/rand"
"fmt"
"math/rand"
"time"
)
func main() {
games := 1000000
var switchWinsCar, keepWinsCar int
for i := 0; i < games; i++ {
// simulate game
carDoor := rand.Intn(3)
firstChoice := rand.Intn(3)
var hostOpens int
if carDoor == firstChoice {
hostOpens = rand.Intn(2)
if hostOpens >= carDoor {
hostOpens++
}
} else {
hostOpens = 3 - carDoor - firstChoice
}
remainingDoor := 3 - hostOpens - firstChoice
games := 100000
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// some assertions that above code produced a valid game state
if carDoor < 0 || carDoor > 2 {
panic("car behind invalid door")
}
if firstChoice < 0 || firstChoice > 2 {
panic("contestant chose invalid door")
}
if hostOpens < 0 || hostOpens > 2 {
panic("host opened invalid door")
}
if hostOpens == carDoor {
panic("host opened door with car")
}
if hostOpens == firstChoice {
panic("host opened contestant's first choice")
}
if remainingDoor < 0 || remainingDoor > 2 {
panic("remaining door invalid")
}
if remainingDoor == firstChoice {
panic("remaining door same as contestant's first choice")
}
if remainingDoor == hostOpens {
panic("remaining door same as one host opened")
}
// tally results
if firstChoice == carDoor {
keepWinsCar++
}
if remainingDoor == carDoor {
switchWinsCar++
}
}
fmt.Println("In", games, "games,")
fmt.Println("switching doors won the car", switchWinsCar, "times,")
fmt.Println("keeping same door won the car", keepWinsCar, "times.")
var switcherWins, keeperWins, shown int
for i := 0; i < games; i++ {
doors := []int{0, 0, 0}
doors[r.Intn(3)] = 1 // Set which one has the car
choice := r.Intn(3) // Choose a door
for shown = r.Intn(3); shown == choice || doors[shown] == 1; shown = r.Intn(3) {}
switcherWins += doors[3 - choice - shown]
keeperWins += doors[choice]
}
floatGames := float32(games)
fmt.Printf("Switcher Wins: %d (%3.2f%%)\n",
switcherWins, (float32(switcherWins) / floatGames * 100))
fmt.Printf("Keeper Wins: %d (%3.2f%%)",
keeperWins, (float32(keeperWins) / floatGames * 100))
}