2011-09-11 7 views
1

ランダムな文字列を作成するには、 という単純なルールを使用することをお勧めします。ランダムな文字列をルールで作成する

例えば

のMac OSXアプリのこのだろう部分(ユーザー定義された長さ、唯一Eを含有することができる、唯一の2-4「S」を含んでいてもよい)、およびユーザー定義された項目はであろうUI。 ユーザーがパラメータを設定し、[生成]ボタンを押します。 出力はNSTextFieldに表示されます。 もちろん、私はUIの部分を扱うことができると思います。誰かがサンプルコードを取り込もうとしている場合にのみ注意してください。おかげさまで

答えて

2

これは機能しますが、理論的には終了しない可能性があることに注意してください。無関係なEsとSsを他の文字に置き換えて強制的に終了させることを検討することをお勧めします。

ユーザーが入力した長さが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); 
     } 
関連する問題