Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to generate random integers within a range in Swift?

Tags:

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.

like image 971
RonH Avatar asked Jun 05 '14 10:06

RonH


People also ask

How do you generate a random number from within a range?

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.

Which method is used to generate a random integer?

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.

How do you generate a random number without duplicates in Swift?

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.


1 Answers

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) } 
like image 192
Jean Le Moignan Avatar answered Oct 01 '22 10:10

Jean Le Moignan