Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_ARITHMETIC when accessing random elements of NSArray

Tags:

objective-c

i'm trying to get the values of an array randomly but i'm getting an error here is my code so far:

NSMutableArray *validMoves = [[NSMutableArray alloc] init];

for (int i = 0; i < 100; i++){
    [validMoves removeAllObjects];

    for (TileClass *t in tiles ) {
        if ([self blankTile:t] != 0) {
            [validMoves addObject:t];
        }
    }

    NSInteger pick = arc4random() % validMoves.count;

    [self movePiece:(TileClass *)[validMoves objectAtIndex:pick] withAnimation:NO];
}
like image 287
Tbt-lion Arman Capistrano Avatar asked Dec 11 '12 01:12

Tbt-lion Arman Capistrano


1 Answers

The error you're getting (an arithmetic exception) is because validMoves is empty and this leads to a division by zero when you perform the modulus operation.

You have to explicitly check for the case of an empty validMoves array. Also you should use arc4random_uniform for avoiding modulo bias.

if (validMoves.count > 0) {
    NSInteger pick = arc4random_uniform(validMoves.count);
    [self movePiece:(TileClass *)[validMoves objectAtIndex:pick] withAnimation:NO];
} else {
   // no valid moves, do something reasonable here...
}

As a final remark not that arc4random_uniform(0) returns 0, therefore such case should be avoided or you'll be trying to access the first element of an empty array, which of course will crash your application.

like image 87
Gabriele Petronella Avatar answered Nov 07 '22 19:11

Gabriele Petronella