forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Contents.swift
53 lines (40 loc) · 1.3 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//: Playground - noun: a place where people can play
import Foundation
func random(_ n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
let numberOfDoors = 3
var rounds = 0
var winOriginalChoice = 0
var winChangedMind = 0
func playRound() {
// The door with the prize.
let prizeDoor = random(numberOfDoors)
// The door the player chooses.
let chooseDoor = random(numberOfDoors)
// The door that Monty opens. This must be empty and not the one the player chose.
var openDoor = -1
repeat {
openDoor = random(numberOfDoors)
} while openDoor == prizeDoor || openDoor == chooseDoor
// What happens when the player changes his mind and picks the other door.
var changeMind = -1
repeat {
changeMind = random(numberOfDoors)
} while changeMind == openDoor || changeMind == chooseDoor
// Figure out which choice was the winner.
if chooseDoor == prizeDoor {
winOriginalChoice += 1
}
if changeMind == prizeDoor {
winChangedMind += 1
}
rounds += 1
}
// Run the simulation a large number of times.
for _ in 1...5000 {
playRound()
}
let stubbornPct = Double(winOriginalChoice)/Double(rounds)
let changedMindPct = Double(winChangedMind)/Double(rounds)
print(String(format: "Played %d rounds, stubborn: %g%% vs changed mind: %g%%", rounds, stubbornPct, changedMindPct))