MontyHallProblem by Swift
ここを参考に
というかそのままSwiftで書いてみた。
import Foundation func game(change:Bool) -> Int { let correct = Int(arc4random_uniform(3)) var choice = Int(arc4random_uniform(3)) //モンティが開くドアの決定 var open = 0 while true { open = Int(arc4random_uniform(3)) if open != choice && open != correct{ break } } if change { for i in 0..<3{ if i != choice && i != open{ choice = i break } } } var point = 0 if choice == correct{ point += 1} return point } var p = 0 let n = 10000 for _ in 0..<n{ p += game(true) } print(Float(p)/Float(n)) p = 0 for _ in 0..<n{ p += game(false) } print(Float(p)/Float(n))
普通に上手くいく。
output
0.6609 0.333 Program ended with exit code: 0