Every now and again, the following comes out as -1
int randomIndex = random() % [directionsArray count] - 1;
The init method for this class is where directionsArray is created and srand() is called. It looks like this
- (id) initSprite
{
if ( ( self = [super initSprite] ) ) {
speed = 1;
directionsArray = [[NSArray arrayWithObjects:STRING_CONSTANT, STRING_CONSTANT, nil] retain];
srand(time(NULL));
[self pickRandomDirection];
}
return self;
}
- (void) pickRandomDirection
{
int randomIndex = random() % [directionsArray count] - 1; // This sometimes comes out as -1??
}
At the moment, I’m working around it by using abs(randomIndex), but that’s cheating and I should probably know what’s going on for future reference.
Because 0 – 1 equals -1.
What if random() returns 0 here ? You get 0%[directionsArray count] – 1; which is -1, since % has precedence over –
Perhaps you want
random() % ([directionsArray count] - 1);