Skip to content

Instantly share code, notes, and snippets.

@jonathanpenn
Last active December 11, 2015 14:09
Show Gist options
  • Save jonathanpenn/4612637 to your computer and use it in GitHub Desktop.
Save jonathanpenn/4612637 to your computer and use it in GitHub Desktop.
Here's how I'm generating a set of 1,000 random strings with between 4 and 14 random lowercase characters. Is there a better way?
@implementation SomeGenerater
- (NSArray *)generateAThousandRandomStrings
{
NSMutableArray *strings = [[NSMutableArray alloc] initWithCapacity:1000];
for (int count = 0; count < 1000; count++) {
int length = arc4random_uniform(10) + 4;
unichar buf[length];
for (int idx = 0; idx < length; idx++) {
buf[idx] = (unichar)('a' + arc4random_uniform(26));
}
[strings addObject:[NSString stringWithCharacters:buf length:length]];
}
return strings;
}
@end
@eraserhd
Copy link

Shortest solution:

t(a,b) { return arc4random_uniform(a)+b; }

- (NSArray *)generateAThousandStrings
{
    NSMutableString *data = [[NSMutableString alloc] initWithCapacity:1000*15];
    for (int i = 1000, e = t(10,5); i || e; --e || --i)
        [data appendFormat:@"%c", e ? t(26,'a') : (e = t(10,5), '/')];
    return [data componentsSeparatedByString:@"/"];
}

@jonathanpenn
Copy link
Author

@eraserhd you have proven yourself with this one. :)

@eraserhd
Copy link

@jonathanpenn There, I extracted a function. Shorter now. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment