Last active
November 26, 2015 16:26
-
-
Save indragiek/b16f95d911a37cb963a7 to your computer and use it in GitHub Desktop.
Random number generator in Swift
This file contains hidden or 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
public struct RandomNumberGenerator: SequenceType { | |
let range: Range<Int> | |
let count: Int | |
public init(range: Range<Int>, count: Int) { | |
self.range = range | |
self.count = count | |
} | |
public func generate() -> GeneratorOf<Int> { | |
var i = 0 | |
return GeneratorOf<Int> { | |
return (i++ == self.count) ? .None : randomNumberFrom(self.range) | |
} | |
} | |
} | |
public func randomNumberFrom(from: Range<Int>) -> Int { | |
return from.startIndex + Int(arc4random_uniform(UInt32(from.endIndex - from.startIndex))) | |
} | |
public func randomNumbersFrom(from: Range<Int>, #count: Int) -> RandomNumberGenerator { | |
return RandomNumberGenerator(range: from, count: count) | |
} | |
// MARK: Usage | |
// Generate multiple random numbers | |
for n in randomNumbersFrom(1...100, count: 10) { | |
print(n) | |
} | |
// Generate a single random number | |
let n = randomNumberFrom(1...10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment