Created
July 7, 2015 17:13
-
-
Save oisdk/b59bc92ac6f372e7abd7 to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
func randomNumber<S : SequenceType where S.Generator.Element == Double> | |
(probabilities: S) -> Int { | |
var sum = 0.0 | |
let accum = probabilities.map { | |
prob -> Double in | |
sum += prob | |
return sum | |
} | |
let rnd = sum * Double(arc4random_uniform(UInt32.max - 1))/Double(UInt32.max) | |
return accum.indexOf { rnd < $0 } ?? accum.count - 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment