0

我有代码,当我按下按钮时,会导致标签发生变化。我曾尝试编写代码以使标签不会连续两次获得相同的值,但它不起作用,因为有时我仍然会连续两次获得相同的值。

什么是正确的解决方案?

这是代码:

- (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)然后将数组随机播放一次。(请参阅什么是洗牌 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;
}
于 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 回答