Skip to content

Instantly share code, notes, and snippets.

@FredrikSjoberg
Last active February 2, 2017 10:37
Show Gist options
  • Save FredrikSjoberg/e5e8e205a62598e03f3347a04f35fcbd to your computer and use it in GitHub Desktop.
Save FredrikSjoberg/e5e8e205a62598e03f3347a04f35fcbd to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Foundation
import GameplayKit
struct Game: Sequence, IteratorProtocol {
// Should return a random Int between 0-Param, ie 0<=x<3
let random: (Int) -> Int
let doors: Int = 3
let limit: UInt
var round: UInt = 1
init(rounds: UInt = 100, random: @escaping (Int) -> Int) {
self.random = random
self.limit = rounds
}
mutating func next() -> Result? {
guard round <= limit else { return nil }
defer { round += 1 }
let price = random(doors)
let choice = random(doors)
// Revealing 1 empty door after initial selection generates a 50/50 probability for switch/stay. Ie: either the initial selection was correct or not, which requires the remaining door to hold the price
return Result(stayWins: choice == price ? 1 : 0,
switchWins: choice != price ? 1 : 0)
}
}
struct Result: CustomStringConvertible {
let stayWins: UInt
let switchWins: UInt
init(stayWins: UInt = 0, switchWins: UInt = 0) {
self.stayWins = stayWins
self.switchWins = switchWins
}
static func + (lhs: Result, rhs: Result) -> Result {
return Result(stayWins: lhs.stayWins+rhs.stayWins,
switchWins: lhs.switchWins+rhs.switchWins)
}
var description: String {
let stay = "Stay Wins: \(Float(stayWins)/Float(stayWins+switchWins)*100)% \n"
let change = "Switch Wins: \(Float(switchWins)/Float(stayWins+switchWins)*100)%"
return stay + change
}
}
let rounds:UInt = 1000
let random = GKLinearCongruentialRandomSource(seed: 1)
let result = Game(rounds: rounds){ random.nextInt(upperBound: $0) }.reduce(Result()){ $0 + $1 }
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment