Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling Letters in an NSString in Objective-C

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;
}
like image 586
jkeesh Avatar asked Sep 10 '10 06:09

jkeesh


2 Answers

A variant of @dreamlax's code that doesn't use char array. Not as efficient for sure. But it doesn't have the Unicode issue.

NSMutableString *randomizedText = [NSMutableString stringWithString:currentText];

NSString *buffer;
for (NSInteger i = randomizedText.length - 1, j; i >= 0; i--)
{
    j = arc4random() % (i + 1);

    buffer = [randomizedText substringWithRange:NSMakeRange(i, 1)];
    [randomizedText replaceCharactersInRange:NSMakeRange(i, 1) withString:[randomizedText substringWithRange:NSMakeRange(j, 1)]];
    [randomizedText replaceCharactersInRange:NSMakeRange(j, 1) withString:buffer];
}
like image 71
pixelfreak Avatar answered Nov 06 '22 10:11

pixelfreak


It would be better to copy the contents of the string into a temporary buffer of type unichar and shuffle the contents of the buffer, instead of creating lots of little strings.

NSUInteger length = [finalLettersString length];

if (!length) return; // nothing to shuffle    

unichar *buffer = calloc(length, sizeof (unichar));

[finalLettersString getCharacters:buffer range:NSMakeRange(0, length)];

for(int i = length - 1; i >= 0; i--){
    int j = arc4random() % (i + 1);
    //NSLog(@"%d %d", i, j);
    //swap at positions i and j
    unichar c = buffer[i];
    buffer[i] = buffer[j];
    buffer[j] = c;
}

NSString *result = [NSString stringWithCharacters:buffer length:length];
free(buffer);

// caution, autoreleased. Allocate explicitly above or retain below to
// keep the string.
finalLettersString = result;

A couple of things you'll have to watch out for:

  1. Unicode strings can contain composite characters and surrogate pairs. Shuffling these around will most likely result in an invalid string. While surrogate pairs are rare, it is not uncommon to find that the character é is composed of two characters (the base lowercase letter e and the combining acute accent).

  2. For large strings it could cause memory problems because you end up using 3 times as much space as the original string (1× for the original string, 2× for the buffer we use, and 3× for the new string, and then back down to 2× once we free the buffer).

like image 31
dreamlax Avatar answered Nov 06 '22 11:11

dreamlax