Skip to content

Instantly share code, notes, and snippets.

@patricklynch
Last active August 29, 2015 14:24
Show Gist options
  • Save patricklynch/a6babe376dd959e60b97 to your computer and use it in GitHub Desktop.
Save patricklynch/a6babe376dd959e60b97 to your computer and use it in GitHub Desktop.
Random Generator
// Generates various types of random values
//
// Created by Patrick Lynch on 6/30/15.
// Copyright © 2015 Patrick Lynch. All rights reserved.
import Foundation
struct Random {
// Designed for you to swap out for any other core random function
private static func _random() -> UInt32 {
return arc4random()
}
static func index( count: Int ) -> Int {
return Int(_random() % UInt32(count))
}
static func index( count: UInt ) -> UInt {
return UInt(_random() % UInt32(count))
}
static func element<T>( collection:[T] ) -> T {
return collection[ index( collection.count ) ]
}
static func bool() -> Bool {
return Bool(_random() % UINT32_MAX > UINT32_MAX / 2)
}
static func probability( probability: Float ) -> Bool {
return self.value( from: 0.0, to: 1.0 ) >= 1.0 - probability
}
static func value( from min: Float = 0.0, to max: Float = 1.0 ) -> Float {
let r = Float(_random() % UINT32_MAX) / Float(UINT32_MAX)
return min + r * (max - min)
}
static func value( from min: Double = 0.0, to max: Double = 1.0 ) -> Double {
let r = Double(_random() % UINT32_MAX) / Double(UINT32_MAX)
return min + r * (max - min)
}
static func value( from min: Int, to max: Int ) -> Int {
return min + Int(_random() % UInt32(max-min))
}
static func value( from min: UInt, to max: UInt ) -> UInt {
return min + UInt(_random() % UInt32(max-min))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment