0

I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?

int r = arc4random() % (9);
    NSLog(@"Random Number: %d",r);
Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556

4 Answers4

15

int r = (arc4random() % 8) + 1

indragie
  • 18,002
  • 16
  • 95
  • 164
  • 1
    This answer wont really work if you're looking to exclude any other number within the range. Sheehan Alams title should have been more specific, such as "I want arc4random to start from 1" or "I want to exclude the first number when using arc4random". Just saying :) – Tommie Feb 22 '13 at 10:20
5

You can use arc4random_uniform(), as in

arc4random_uniform(9) + 1

Generally, to generate a number between lo and hi (inclusive), you use:

arc4random_uniform(hi - lo + 1) + lo

If you don't want to use arc4random_uniform() and want to stick with arc4random(), noting that the resulting value from using modulus formula is not uniformly distributed, use

(arc4random() % (hi - lo + 1)) + lo
pmg
  • 106,608
  • 13
  • 126
  • 198
1

int r = arc4random() % 8 + 1;

See other answers (e.g., one from me) for why you probably don't want to use % for this task, and what you should use instead.

Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

You could simply try repeatedly until you get a number in the range you want, throwing out numbers you don't want. This has the fancy name "acceptance-rejection method" in math. It's simple, and it works.

In case you're worried that this could take a long time, in theory it could. But this approach is used all the time in statistical applications. The probability of going through a while-loop N times decreases rapidly as N increases, so the average number of times through the loop is small.

John D. Cook
  • 29,517
  • 10
  • 67
  • 94