开发者

Create random string of characters, with rules

开发者 https://www.devze.com 2023-04-04 14:25 出处:网络
I would like to know the best way to create a random string of characters, but with some simple rules.

I would like to know the best way to create a random string of characters, but with some simple rules.

for example: ( User defined length, may only contain one E, may only contain 2-4 'S' )

This 开发者_高级运维would part of a Mac OSX app, and the User defined items would be in UI. User sets parameters and presses "Generate" button. The output is displayed in a NSTextField. Of course I think I can handle the UI part, only noted incase someone wants to include sample code. Thanks.


This works, but be aware that theoretically, it might not terminate. You might want to consider replacing extraneous Es and Ss with other letters to force it to terminate.

It would definitely loop forever if the user inputted length was 2!

        BOOL canQuit = NO;
        while (!canQuit)
        {
            NSMutableString *output = [[[NSMutableString alloc] init] autorelease];
            while ([output length] < userDefinedLength)
            {
                //Generates a random character between a and z;
                char c = ((arc4random() % (122 - 96)) + 97);
                [output appendFormat:@"%c", c];
            }
            NSLog(@"%@", output);
            int numberOfE = [output replaceOccurrencesOfString:@"e" withString:@"e" options:NSCaseInsensitiveSearch range:NSMakeRange(0, output.length)];
            int numberOfS = [output replaceOccurrencesOfString:@"s" withString:@"s" options:NSCaseInsensitiveSearch range:NSMakeRange(0, output.length)];

            canQuit = (numberOfE <= 1 && numberOfS >= 2 && numberOfS <= 4);
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消