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>
- …
I hope I won’t dissapoint You if I don’t include any sample project this time. For one simple function returning an integer 7 examples should be enough.
I genuinely enjoy examining on this site, it has excellent content. “A short saying oft contains much wisdom.” by Sophocles.
look videos watch
Nice way to have random numbers [5,14] such as:
5 + arc4random() % 10
Thanks.
how to random float number from 0.5 to 2.0
Check this: http://www.daniweb.com/forums/thread98545.html
or google for more. It’s more typical task for all C programmers, rather than iPhone devs.
float initRan;
initRan = 5 + arc4random() % 16;
myRandomNumber = initRan / 10;
I use this
x = arc4random()% 480;
and I get sometimes numbers that 500+ ?
how can it be?
x is an integer? otherwise it’s not possible
% in this case gives you the rest from division so:
5 % 3 = 2
18 % 4 = 2 (18 – 4×4 = 2)
20 % 4 = 0 (20 – 4×5 = 0);
6 % 3 = 6 (6 – 3×0 = 6);