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];
}
The error you’re getting (an arithmetic exception) is because
validMovesis 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
validMovesarray.Also you should use
arc4random_uniformfor avoiding modulo bias.As a final remark not that
arc4random_uniform(0)returns0, 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.