Created
September 2, 2015 12:55
-
-
Save ytkhs/9164a61994b2d47e6f18 to your computer and use it in GitHub Desktop.
モンティ・ホール問題の検証 written in Go
This file contains hidden or 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" | |
) | |
func shuffle(a map[int]bool) { | |
rand.Seed(time.Now().UnixNano()) | |
for i := range a { | |
j := rand.Intn(i + 1) | |
a[i], a[j] = a[j], a[i] | |
} | |
} | |
func main() { | |
counter1 := 0 | |
counter2 := 0 | |
loop := 100000 | |
for i := 0; i < loop; i++ { | |
// 全3個あたりがひとつのくじを用意 | |
lottery := map[int]bool{0: true, 1: false, 2: false} | |
// シャッフル | |
shuffle(lottery) | |
// ひとつ選ぶ | |
choice := rand.Intn(3) | |
// 選びなおさない場合、当たっていたらカウント | |
if lottery[choice] == true { | |
counter1++ | |
} | |
// 選んでないものからハズレをひとつ取り除く | |
for k, v := range lottery { | |
if (k != choice) && v == false { | |
delete(lottery, k) | |
break | |
} | |
} | |
// 残っている方に選びなおす | |
for k := range lottery { | |
if k != choice { | |
choice = k | |
break | |
} | |
} | |
// 選びなおした場合、当たっていたらカウント | |
if lottery[choice] == true { | |
counter2++ | |
} | |
} | |
// 普通に選んだ場合 | |
fmt.Println(counter1) | |
// 選びなおした場合 | |
fmt.Println(counter2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment