GENERATING RANDOM NUMBERS IN OBJECTIVE-C

Pooja Malohtra

Total Post:47

Points:331
Posted by  Pooja Malohtra
 1082  View(s)
Ratings:
Rate this:

I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)

I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured The Google, and it just seems to be lots of different and conflicting bits of information.

  1. Jessica James

    Post:16

    Points:114
    Re: Generating Random Numbers in Objective-C

    Use the arc4random_uniform(upper_bound) function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.

     

    arc4random_uniform(74)

     

    arc4random_uniform(upper_bound) avoids modulo bias

     

    arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

      Modified On Mar-18-2016 11:21:30 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!