Wednesday, 25 May 2011

How to get Random numbers in iphone?

If you are creating an app with dynamical content, plot, random number is something definitely you need to know. Random number of enemies, random score for each smaller achievement, random number… forget about the reasons you need to know it!

There are few functions in iPhone SDK that gives you random number. The best is arc4random(). Why best? Because, each time you call this function you get the random number, without performing any other randomize procedures.

int myRandomNumber;
myRandomNumber = arc4random();
int myRandomNumber2;
myRandomNumber2 = arc4random();
In above example myRandomNumber and myRandomNumber2 are two different integers, it will be amazing coincident if they are the same.

There is one thing you need to know about it. arc4random() doesn’t ask you about the range of given number, in fact in most cases it returns you the random 8-9 digits numbers (positive or negative). But, using (un)known modulo operation (returns the remainder of division) you can get:

arc4random() % 10 : random number from range <0, 9>
arc4random() % 11 : random number from range <0, 10>
arc4random() % 2 : random number from range <0, 1>
arc4random() % 1000 : random number from range <0, 999>
arc4random() % 1001 : random number from range <0, 1000>
Now, using the know addition you can generate any range you wish:

5 + arc4random() % 10 : <5,14>
100 + arc4random() % 15 : <100,114>

No comments:

Post a Comment