I have written this function which shuffles the contents of a NSString
, and it seems to work, but every now and then it crashes. This may be a roundabout way, but I put the characters into an array, swap the elements in the array randomly, and then turn the array back into a string.
I'm not sure what I am doing that is unsafe which makes it crash. I thought it was possibly that I am setting finalLettersString = result
, but I also tried finalLettersString = [NSString stringWithString:result]
and that also crashes. The reason I am confused is because it does not crash every time. I just keep pressing the shuffle button, and sometimes it crashes. Any places I should look?
/* This function shuffles the letters in the string finalLettersString */
-(IBAction)shuffleLetters:(id)sender{
int length = [finalLettersString length];
NSMutableArray * letters = [NSMutableArray arrayWithCapacity:length];
NSLog(@"final letters: %@", finalLettersString);
for(int i = 0; i < length; i++){
char ch = [finalLettersString characterAtIndex:i];
NSLog(@"%c", ch);
NSString * cur = [NSString stringWithFormat:@"%c", ch];
[letters insertObject:cur atIndex:i];
}
NSLog(@"LETTERS:: %@", letters);
for(int i = length - 1; i >= 0; i--){
int j = arc4random() % (i + 1);
//NSLog(@"%d %d", i, j);
//swap at positions i and j
NSString * str_i = [letters objectAtIndex:i];
[letters replaceObjectAtIndex:i withObject:[letters objectAtIndex:j]];
[letters replaceObjectAtIndex:j withObject:str_i];
}
NSLog(@"NEW SHUFFLED LETTERS %@", letters);
NSString * result = @"";
for(int i = 0; i < length; i++){
result = [result stringByAppendingString:[letters objectAtIndex:i]];
}
NSLog(@"Final string: %@", result);
finalLettersString = result;
finalLetters.text = finalLettersString;
}