0

ボタンを押すとラベルが変わるコードがあります。ラベルが 2 回続けて同じ値を取得しないようにコードを記述しようとしましたが、2 回続けて同じ値が取得されることがあるため、うまくいきませんでした。

正しい解決策は何ですか?

これはコードです:

- (IBAction)buttonPressed:(id)sender {
    if (sender == self.button) {
        // Change the randomLabel by right answer
        NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
        words = [[NSMutableArray alloc] initWithContentsOfFile:path];
        NSString *generateRandomLabel = [NSString stringWithFormat:@"%@", [words objectAtIndex:arc4random_uniform([words count] - 1)]];

        if ([randomLabel.text isEqualToString:generateRandomLabel]) {
            while ([randomLabel.text isEqualToString:generateRandomLabel]) {
                generateRandomLabel = [NSString stringWithFormat:@"%@", [words objectAtIndex:arc4random_uniform([words count] - 1)]];
            }
        } else if (![randomLabel.text isEqualToString:generateRandomLabel]) {
            [self.randomLabel setText:generateRandomLabel];
            [randomLabel.text isEqualToString:generateRandomLabel];
        }
    }
4

2 に答える 2

3

問題は、ランダム関数がランダムな値を生成していることですが、同じ値をn回生成することを妨げるものは何もありません。配列またはセットは関係ありません

繰り返さないランダムアルゴリズムが必要です:

1)毎回新たにロードするのではなく、一度ロードしたアレイを保持する必要があります

2) 次に、配列を 1 回シャッフルします。( NSMutableArray をシャッフルする最良の方法を参照してください。 )

3)ボタンを押すと、配列内の 0 オブジェクトを使用し、それを削除して最後に再読み込みします

mock-code: 少なくとも 2 つの異なる単語を含む単語ファイル > 1 を想定

- init {
    self = [super init];
    words = [self loadWordsFromFile];
    [words shuffle];
}

- onButtonPress {
    id word = nil;
    do { 
        [words objectAtIndex:0];
        [words removeObjectAtIndex:0];
        [words addObject:word];
    while([word isEqualToString:[words objectAtIndex:0])
    label.text = word;
}
于 2012-12-06T14:28:01.843 に答える
1

これは、乱数ジェネレーターに配列の最後のメンバーを除くすべてのメンバーから選択させ、選択したメンバーを配列の最後の項目と交換させることで、非常に簡単に行うことができます。

- (IBAction)buttonPressed:(id)sender {
    if (! words) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
        words = [[NSMutableArray alloc] initWithContentsOfFile:path];
    }
    NSInteger index = arc4random_uniform(words.count - 2);
    randomLabel.text = words[index];
    [words exchangeObjectAtIndex:index withObjectAtIndex:words.count-1];
}
于 2012-12-06T16:42:45.337 に答える