Created
December 22, 2014 08:23
-
-
Save Hysteria/9bff6268cfa94439ec57 to your computer and use it in GitHub Desktop.
Dice example in swift
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
protocol RandomNumberGenerator { | |
func random() -> Double | |
} | |
class LinearCongruentialGenerator : RandomNumberGenerator { | |
var lastRandom = 42.0 | |
let m = 139969.0 | |
let a = 3877.0 | |
let c = 29573.0 | |
func random() -> Double { | |
lastRandom = ((lastRandom * a + c) % m) | |
return lastRandom / m | |
} | |
} | |
class Dice { | |
let sides: Int | |
let generator: RandomNumberGenerator | |
init(sides: Int, generator: RandomNumberGenerator) { | |
self.sides = sides | |
self.generator = generator | |
} | |
func roll() -> Int { | |
return Int(generator.random() * Double(sides | |
)) + 1 | |
} | |
} | |
let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) | |
dice.roll() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment