Skip to content

Instantly share code, notes, and snippets.

@ispeedyg
Forked from Hysteria/Dice.swift
Created September 23, 2015 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ispeedyg/8d7af647bf605fd7d396 to your computer and use it in GitHub Desktop.
Save ispeedyg/8d7af647bf605fd7d396 to your computer and use it in GitHub Desktop.
Dice example in swift
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