Created
February 5, 2019 02:56
-
-
Save tailnode/a9b750c920ef03e5c86e8b4590c42b38 to your computer and use it in GitHub Desktop.
monty_hall
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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
const doorCount = 3 | |
const ( | |
sheep = iota | |
car | |
) | |
var doors = [doorCount]int{} | |
type input struct { | |
retry bool | |
win bool | |
} | |
var outputTemplate = ` | |
retry | Y | N | |
win \| | |
Y | %d| %d | |
N | %d| %d` | |
func main() { | |
Init() | |
result := map[input]int{} | |
for i := 0; i < 10000; i++ { | |
retry := i&1 == 1 | |
win := oneLoop(retry) | |
result[input{ | |
retry: retry, | |
win: win, | |
}]++ | |
} | |
fmt.Printf(outputTemplate, result[input{retry: true, win: true}], result[input{win: true}], result[input{retry: true}], result[input{}]) | |
} | |
func Init() { | |
rand.Seed(time.Now().Unix()) | |
} | |
func resetDoors() { | |
carIndex := rand.Intn(doorCount) | |
for i := range doors { | |
doors[i] = sheep | |
} | |
doors[carIndex] = car | |
} | |
func firstSelect() int { | |
return rand.Intn(doorCount) | |
} | |
func openADoor(excludeIndex int) int { | |
if doors[excludeIndex] == car { | |
n := rand.Intn(doorCount - 1) | |
if n >= excludeIndex { | |
return n + 1 | |
} | |
return n | |
} | |
for i := range doors { | |
if i != excludeIndex && doors[i] == sheep { | |
return i | |
} | |
} | |
panic("should not happen") | |
} | |
func reSelect(a, b int) int { | |
for i := range doors { | |
if i != a && i != b { | |
return i | |
} | |
} | |
panic("should not happen") | |
} | |
func oneLoop(retry bool) (win bool) { | |
resetDoors() | |
selectI := firstSelect() | |
openI := openADoor(selectI) | |
if retry { | |
selectI = reSelect(selectI, openI) | |
} | |
return doors[selectI] == car | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment