iPhone Development – Generating random numbers

this is a very short trick for generating random numbers when developing for iphone. There are many ways but this worked very fine for me and has some advantages over other methods here are some examples :


NSInteger randomNumber0_100 = arc4random()%100;

NSInteger randomNumber50_100 = arc4random()%50 + 50;

CGFloat randomFloat0_1 = (float)(arc4random()%100/100.0f);

There are 3 examples which show how to generate different ranges of random values.

The arc4random() function uses the key stream generator employed by the
arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about
(2**1700) states. The arc4random() function returns pseudo-random num-bers numbers
bers in the range of 0 to (2**32)-1, and therefore has twice the range of
rand(3) and random(3).

Leave a Reply