The method I've devised so far is this:
func randRange (lower : Int , upper : Int) -> Int { let difference = upper - lower return Int(Float(rand())/Float(RAND_MAX) * Float(difference + 1)) + lower }
This generates random integers between lower and upper inclusive.
Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
random() returns a double value between 0 and 1, which can be used to generate random integers but is not suitable. 2) The preferred way to generate random integer values is by using the nextInt(bound) method of java. util. Random class.
Put all the values you want into an array, generate a random number using arc4random_uniform(SIZEOFARRAY) and pull the index of the random value from the array, and then repeat this process until the array is empty.
Here's a somewhat lighter version of it:
func randRange (lower: Int , upper: Int) -> Int { return lower + Int(arc4random_uniform(UInt32(upper - lower + 1))) }
This can be simplified even further if you decide this function works with unsigned values only:
func randRange (lower: UInt32 , upper: UInt32) -> UInt32 { return lower + arc4random_uniform(upper - lower + 1) }
Or, following Anton's (+1 for you) excellent idea of using a range as parameter:
func random(range: Range<UInt32>) -> UInt32 { return range.startIndex + arc4random_uniform(range.endIndex - range.startIndex + 1) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With