Last active
December 11, 2015 14:09
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 |
@kconner ha! If I was going for speed I might even try to use malloc()
instead. :) I'm going for purity more as part of an exercise in readable, idiomatic Objective C. The speed and memory concerns didn't matter. I just didn't want to bog down the reader of the example with extra stuff.
@aglee, this is MUCH better! It's just enough C that it won't detract from the larger concept I'm trying to get at. I think I'm going with this.
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:@"/"];
}
@eraserhd you have proven yourself with this one. :)
@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
FWIW here's the array-of-unichar code I tested with: