Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "math/rand"
- )
- // Possible entries
- const Car = 0
- const Goat = 1
- // Possible results
- const ChoiceWin = 1
- const ChoiceLose = 2
- const ChoiceInvalid = 3
- /*
- * Create int[3] with two Goats and one Car
- * @returns []int
- */
- func makeMonty() []int {
- monty := []int{
- Car,
- Car,
- Car,
- }
- // Attempt to randomize two indexes
- goatIdx1 := rand.Intn(len(monty))
- goatIdx2 := rand.Intn(len(monty))
- // It's possible to have two of the same so keep going until it works
- for goatIdx2 == goatIdx1 {
- goatIdx2 = rand.Intn(len(monty))
- }
- // Make ze goat
- monty[goatIdx1] = Goat
- monty[goatIdx2] = Goat
- return monty
- }
- /*
- * Randomly "reveal" first item of monty and return index and value
- */
- func reveal(choice int, monty []int) (int, int) {
- revealIdx := choice
- for revealIdx == choice {
- revealIdx = rand.Intn(len(monty))
- }
- return revealIdx, monty[revealIdx]
- }
- /*
- * Make choice and stick to it (statistically wrong)
- */
- func chooseWrong(monty []int) int {
- choice := rand.Intn(len(monty))
- _, revealVal := reveal(choice, monty)
- // If revealed tile is the winner we wont reach the puzzle
- if revealVal != Car {
- if monty[choice] == Car {
- return ChoiceWin
- } else {
- return ChoiceLose
- }
- }
- return ChoiceInvalid
- }
- /*
- * Make choice and change (statistically right)
- */
- func chooseRight(monty []int) int {
- choice := rand.Intn(len(monty))
- revealIdx, revealVal := reveal(choice, monty)
- if revealVal != Car {
- choiceNew := 0
- for (choiceNew == choice || choiceNew == revealIdx) {
- choiceNew++
- }
- if monty[choiceNew] == Car {
- return ChoiceWin
- } else {
- return ChoiceLose
- }
- }
- return ChoiceInvalid
- }
- /*
- * Calls $fn $count times and output results as formatted string to $ch
- */
- func chooseGo(ch chan string, count int, name string, fn func([]int) int) {
- winCount := 0
- lossCount := 0
- validCount := 0
- for i := 0; i < count; i++ {
- ret := fn(makeMonty())
- if (ret == ChoiceWin) {
- winCount++
- validCount++
- } else if (ret == ChoiceLose) {
- lossCount++
- validCount++
- }
- }
- // Whoa
- ch <-
- fmt.Sprintln(name) +
- fmt.Sprintln(" win%: ", float64(winCount) / float64(validCount)) +
- fmt.Sprintln(" wins: ", winCount) +
- fmt.Sprintln(" losses: ", lossCount) +
- fmt.Sprintln(" total: ", validCount)
- }
- func main() {
- ch := make(chan string)
- count := 5000000 // big number
- go chooseGo(ch, count, "wrong", chooseWrong)
- go chooseGo(ch, count, "right", chooseRight)
- message := <- ch
- fmt.Println(message)
- message = <- ch
- fmt.Println(message)
- }
Add Comment
Please, Sign In to add comment