Skip to content

Instantly share code, notes, and snippets.

@tiktuk
Forked from JadenGeller/Random.swift
Last active October 8, 2015 10:28
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 tiktuk/1dd83e6cdd2fede38be7 to your computer and use it in GitHub Desktop.
Save tiktuk/1dd83e6cdd2fede38be7 to your computer and use it in GitHub Desktop.
Random Numbers in Swift
struct Random {
static func within<B: protocol<Comparable, ForwardIndexType>>(range: ClosedInterval<B>) -> B {
let inclusiveDistance = range.start.distanceTo(range.end).successor()
let randomAdvance = B.Distance(arc4random_uniform(UInt32(inclusiveDistance.toIntMax())).toIntMax())
return range.start.advancedBy(randomAdvance)
}
static func within(range: ClosedInterval<Float>) -> Float {
return (range.end - range.start) * Float(Float(arc4random()) / Float(UInt32.max)) + range.start
}
static func within(range: ClosedInterval<Double>) -> Double {
return (range.end - range.start) * Double(Double(arc4random()) / Double(UInt32.max)) + range.start
}
static func generate() -> Int {
return Random.within(0...1)
}
static func generate() -> Bool {
return Random.generate() == 0
}
static func generate() -> Float {
return Random.within(0.0...1.0)
}
static func generate() -> CGFloat {
return CGFloat(Random.within(0.0...1.0))
}
static func generate() -> Double {
return Random.within(0.0...1.0)
}
}
// Example
while true { println(Random.within(2.3...5.7)) }
/* -> 2.98055791377103
* 3.29764970182386
* 3.46185294840528
* 4.50507207708551
* 4.7390977582054
* 4.98469445493182
* 3.17118956238758
* 4.88981824288839
* 4.35301200199244
* 2.87590078748201
* 5.20722583832853
* 4.98944639761221
* 3.90587487821604
* 3.97134446820043
* 2.6031687081566
* 2.98006869556384
* 2.9983296749411
* 2.72558503174819
* 2.30275103338127
* 5.17898262280016
* ...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment