如何获取不连续两次相同的数组值

我有代码,当我按下一个button,导致标签改变。 我试图写代码,以便标签不连续两次获得相同的值,但它不工作,因为我有时连续两次获得相同的值。

什么是正确的解决scheme?

这是代码:

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

你可以非常简单地做到这一点,让你的随机数发生器从数组中的所有成员中select,除了最后一个数组以外,然后用数组中的最后一项交换你select的数组:

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

问题是随机函数正在生成一个随机值,但是没有任何东西使它不会产生相同的值n次。 数组或集合没有关系

你需要一个非重复的随机algorithm:

1)你应该保持数组加载一次,而不是每次重新加载

2)然后SHUFFLEarrays一次。 (请参阅“洗牌NSMutableArray的最佳方法是什么?” )

3)然后按下button,使用数组中的0对象,删除它并在最后读取它

模拟代码:假定单词文件> 1,至less有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; }