问题应用程序没有重复

时间:2012-11-15 14:27:38

标签: iphone objective-c

我想制作一个问题应用程序,它显示了我制作的一个plist的随机问题。这是功能(现在只有7个问题)。

我的函数提出了一个随机问题,但它始终以相同的问题开头 并且可以重复一个问题。我需要你的帮助来随机生成问题而不重复。

 currentQuestion=rand()%7;
 NSDictionary *nextQuestion = [self.questions objectAtIndex:currentQuestion];

    self.answer = [nextQuestion objectForKey:@"questionAnswer"];

    self.qlabel.text = [nextQuestion objectForKey:@"questionTitle"];

    self.lanswer1.text = [nextQuestion objectForKey:@"A"];

    self.lanswer2.text = [nextQuestion objectForKey:@"B"];

    self.lanswer3.text = [nextQuestion objectForKey:@"C"];

    self.lanswer4.text = [nextQuestion objectForKey:@"D"];

3 个答案:

答案 0 :(得分:2)

rand()%7;将始终生成一个独特的随机数序列。

改为使用arc4random() % 7;

currentQuestion=arc4random() %7;

答案 1 :(得分:2)

我会这样做(在ARC中,为了清晰起见而写得太长了):

@property (nonatomic,strong) NSDictionary *unaskedQuestions;

- (NSString *)nextRandomUnaskedQuestion {

    if (!self.unaskedQuestions) {
        // using your var name 'nextQuestion'.  consider renaming it to 'questions'
        self.unaskedQuestions = [nextQuestion mutableCopy];
    }

    if ([self.unaskedQuestions count] == 0) return nil;  // we asked everything

    NSArray *keys = [self.unaskedQuestions allKeys];
    NSInteger randomIndex = arc4random() % [allKeys count];
    NSString *randomKey = [keys objectAtIndex:randomIndex];
    NSString *nextRandomUnaskedQuestion = [self.unaskedQuestions valueForKey:randomKey];

    [self.unaskedQuestions removeObjectForKey:randomKey];
    return nextRandomUnaskedQuestion;
}

答案 2 :(得分:1)

  1. 使用问题数组的数组。假设您有名为arrKeys的数组 - > [A],[B],[C],[D],...,[z],nil
  2. 使用(arc4random()%array.length-1){由Suresh建议}为您的数组生成重新随机索引。假设你有rand = 3
  3. 从数组中获取密钥arrKeys @ 3 = D.然后从NSDictionary中使用[nextQuestion objectForKey:@“D”]并从数组中删除'D'键为[arrKeys removeObjectAtIndex:3]。下一个问题重复1-3步。