Skip to content

Instantly share code, notes, and snippets.

@oisdk
Created July 7, 2015 17:13
Show Gist options
  • Save oisdk/b59bc92ac6f372e7abd7 to your computer and use it in GitHub Desktop.
Save oisdk/b59bc92ac6f372e7abd7 to your computer and use it in GitHub Desktop.
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