Objective C – Random Character Generator

 

– (NSString *)shuffledAlphabet {

//    NSString *alphabet = @”ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

//

//    // Get the characters into a C array for efficient shuffling

//    NSUInteger numberOfCharacters = [alphabet length];

//    unichar *characters = calloc(numberOfCharacters, sizeof(unichar));

//    [alphabet getCharacters:characters range:NSMakeRange(0, numberOfCharacters)];

//

//    // Perform a Fisher-Yates shuffle

//    for (NSUInteger i = 0; i < numberOfCharacters; ++i) {

//        NSUInteger j = (arc4random_uniform(numberOfCharacters – i) + i);

//        unichar c = characters[i];

//        characters[i] = characters[j];

//        characters[j] = c;

//    }

//

//    // Turn the result back into a string

//    NSString *result = [NSString stringWithCharacters:characters length:numberOfCharacters];

//    free(characters);

//    return result;

const NSUInteger length = ‘Z’ – ‘A’ + 1;

unichar alphabet[length];

alphabet[0] = ‘A’;

for ( NSUInteger i = 1; i < length; i++ )

{

NSUInteger j = arc4random_uniform((uint32_t)i + 1);

alphabet[i] = alphabet[j];

alphabet[j] = ‘A’ + i;

}

return [NSString stringWithCharacters:alphabet length:length];

}


Discover more from My Tricky Notes

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Discover more from My Tricky Notes

Subscribe now to keep reading and get access to the full archive.

Continue reading