Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active May 25, 2017 20:23
Show Gist options
  • Save JadenGeller/407036af08a28513eef2 to your computer and use it in GitHub Desktop.
Save JadenGeller/407036af08a28513eef2 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() -> 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
* ...
*/
@tiktuk
Copy link

tiktuk commented Oct 8, 2015

Added a generate() for CGFloats at https://gist.github.com/tiktuk/1dd83e6cdd2fede38be7 ☺️ .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment