0

Alright, so I'm using arc4random to get a random image out of an array, the code for this is as follows:

//ray is the array that stores my images
int pic = arc4random() % ray.count; 
tileImageView.image = [ray objectAtIndex:pic-1];
NSLog(@"Index of used image: %d", pic-1);

I'm calling this code multiple times and it works for a while but after some time it always crashes because of this error:

 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** - [__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 39]'

My question is, why is this ridiculously large number created? Is there something wrong with the arc4random function? Any help would be greatly appreciated

kopproduction
  • 465
  • 5
  • 19

3 Answers3

2

You can also 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 as described in the man page:

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.
Himanshu A Jadav
  • 2,286
  • 22
  • 34
0

arc4random is returning either 0 or an even multiple of ray.count. So when you mod it by ray.count, you get 0. You then subtract 1 from this, getting -1, which translates to a very large unsigned integer.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • Ah, thank you very much! So the right way to do it would be `int pic = arc4random() % (ray.count -1);`, no? – kopproduction Oct 15 '11 at 23:09
  • @kopproduction: If you want to return a random item from the array, you don't need to subtract anything. The modulus operator already ensures that the index is less than ray.count. – Chuck Oct 15 '11 at 23:13
0

The problem is that because your pic-1 construction generates -1 once for a while (which is 4294967295 in unsigned form). You need to get rid of pic-1 and simply use pic instead.

interrupt
  • 2,030
  • 17
  • 14