0

I'm not sure how to format arc4Random() to generate random numbers between 200 and 300. I would like numbers like 200, 210, 220 and so on.. (not 200, 201, 202, ...) (Xcode 5.1.1, iOS)

Any idea?

My piece of code:

self.currentObstacX += arc4random()%(200+10) + 300;

... but it looks like it does not work how I need.

Thank you in advance.

Paul R
  • 208,748
  • 37
  • 389
  • 560
Jiri Svec
  • 147
  • 1
  • 1
  • 12

2 Answers2

2

@PaulR answer will work but it is better to use arc4random_uniform like this...

NSInteger number = 10 * arc4random_uniform(11) + 200;

From the docs...

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.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 1
    @PaulR it was pointed out to me on SO a while ago and I've stuck by it ever since :D Easier to read as well I think. – Fogmeister Sep 15 '14 at 14:18
  • 1
    Evidently I'm a slow learner as this same thing was pointed out to me some time ago also: http://stackoverflow.com/a/20267313/253056 (see bottom comment) ;-) – Paul R Sep 15 '14 at 14:22
1

Try this:

int x = 10 * (arc4random() % 11) + 200; // x = 10 * (0..10) + 200
Paul R
  • 208,748
  • 37
  • 389
  • 560