views:

69

answers:

1

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;
}
+2  A: 

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).

dreamlax
Thanks! Definitely a much better solution. One problem actually was that you can't use NSUIntegers, because -- on 0 leads to a really big number and not -1 since its unsigned. I got it to work using ints and retaining. In this situation, do you think it is preferable to retain or allocate explicitly?
jkeesh
@jkeesh: Good point about the unsigned integers. With regards to allocating explicitly, it depends on the target platform. If you are targeting the iPhone, some say to avoid the autorelease pool when you can elegantly do so, but for Mac OS X (i.e. systems with much more memory than the iPhone) it will make no noticeable difference. Personally, I always allocate explicitly rather than countering an `autorelease` with a `retain`, but the outcome is the same either way.
dreamlax
In this day and age of internationalisation, you can't assume that one unichar maps to one character.
JeremyP
@JeremyP: That's what I was getting at with the first of the gotchas that I listed.
dreamlax