0

How can I create a random number within a range? I tried following code but it didn't accomplish my task.

int fromNumber = 10;
int toNumber = 30;
int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber; 
BergQuester
  • 6,167
  • 27
  • 39
Shairjeel ahmed
  • 51
  • 2
  • 11

2 Answers2

4

There are seven numbers between 4 and 10 inclusive. arc4random_uniform() is recommended over arc4random() for this purpose.

int randomNumber = arc4random_uniform(7) + 4

The more general case is arc4random_uniform(upper_bound - lower_bound + 1) + lower_bound.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
1

Update
I was unaware of arc4random_uniform() before so i recommend https://stackoverflow.com/a/18262992/2611613 as the answer. The answer i linked below still has a good explanation of a general approach to this problem without worrying about languages.


Your answer should work. Without knowing what is wrong with what you have i can only guess at the problem.

Currently you have

int randomNumber = ( arc4random() % ( toNumber - fromNumber ) ) + fromNumber; 

This produces a range [from-to) exclusive where you will never get the value toNumber. If you want your random number be able to get include toNumber

int randomNumber = ( arc4random() % ( toNumber - fromNumber + 1 ) ) + fromNumber; 

With this you would get a range [from-to] inclusive.

You might look at https://stackoverflow.com/a/363732/2611613 for a really good explanation of how this works.

Community
  • 1
  • 1
Iddillian
  • 195
  • 7