Objective-C Avoid repeating random number

May 25, 2009 § 5 Comments

arc4random() is designed for cryptographic cases. If you use random(), then you would have to seed it with current time. It is random generator.

If you do not want the random number to repeat, use a condition to trigger the random().

int lastNumber;
int rNumber;

While (rNumber == lastNumber)
rNumber = arc4random() % 10;
lastNumber = rNumber;

Advertisements

§ 5 Responses to Objective-C Avoid repeating random number

  • Laurent says:

    is arc4random() slower than random?

    • svwebbuilder says:

      Is not about speed? It is just another approach to generate random number.

      arc4random() is decent pseudo-random algorithm and has twice the range or rand().

      On the iPhone, RAND_MAX is 0x7fffffff (2147483647), while arc4random() will return a maximum value of 0x100000000 (4294967296), giving much more precision. No need to seed arc4random(), as the first call to it automatically seeds it.

  • praveen says:

    int lastNumber;
    int rNumber;

    While (rNumber == lastNumber)
    rNumber = arc4random() % 10;
    lastNumber = rNumber;

    i used above code in my proj……..still iam getting repeatation

  • John says:

    I have tried to use this code, but I am getting some errors. Would it be possible for me to email you an example of my code for you to point out what i’m doing wrong?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Objective-C Avoid repeating random number at Web Builders.

meta

%d bloggers like this: