Generate Random Numbers Between Two Numbers in Objective-C Generate Random Numbers Between Two Numbers in Objective-C objective-c objective-c

Generate Random Numbers Between Two Numbers in Objective-C


You could simply use integer values like this:

int lowerBound = ...int upperBound = ...int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);

Or if you mean you want to include float number between lowerBound and upperBound? If so please refer to this question: https://stackoverflow.com/a/4579457/1265516


The following code include the minimum AND MAXIMUM value as the random output number:

- (NSInteger)randomNumberBetween:(NSInteger)min maxNumber:(NSInteger)max{    return min + arc4random_uniform((uint32_t)(max - min + 1));}

Update:
I edited the answer by replacing arc4random() % upper_bound with arc4random_uniform(upper_bound) as @rmaddy suggested.
And here is the reference of arc4random_uniform for the details.

Update2:
I updated the answer by inserting a cast to uint32_t in arc4random_uniform() as @bicycle indicated.


-(int) generateRandomNumberWithlowerBound:(int)lowerBound                               upperBound:(int)upperBound{    int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);    return rndValue;}