簡體   English   中英

如何連續獲取兩次相同的數組值

[英]How to get not twice the same array value in a row

我有代碼,當我按下一個按鈕時,該代碼會導致標簽更改。 我試圖編寫代碼,以使標簽不能連續兩次獲得相同的值,但是它卻行不通,因為有時我仍然連續兩次獲得相同的值。

什么是正確的解決方案?

這是代碼:

- (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];
        }
    }

問題是隨機函數正在生成一個隨機值,但是沒有什么可以阻止它生成n次相同的值。 數組或集合無關緊要

您需要一個非重復的隨機算法:

1)您應該保持陣列加載一次,而不是每次都重新加載

2),然后將數組換組一次。 (請參閱洗牌NSMutableArray的最佳方法是什么?

3)然后按一下按鈕,使用數組中的0對象,將其刪除並最后讀取

模擬代碼:假設單詞文件> 1,至少2個不同的單詞

- 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;
}

您可以非常簡單地執行此操作,方法是讓您的隨機數生成器從數組中除最后一個之外的所有成員中選取,然后將您選擇的那個與數組中的最后一項進行交換:

- (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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM