0

我目前正在制作一个测验应用程序。当用户开始测验时,随机问题会像您对测验应用程序所期望的那样显示。问题是,它不是完全随机的。它确实显示随机问题,但问题重复。我想确保他们直到最后都不会重复!我的代码是:

int Questions = arc4random_uniform(142);
switch (Questions) {
    case 0:

        break;

    case 1:
        break;

(...)

难道没有更好的方法吗?一种不重复问题的方法?太感谢了!

4

4 回答 4

2

洗牌可能是您最好的解决方案:

// Setup
int questionCount = 10; // real number of questions
NSMutableArray *questionIndices = [NSMutableArray array];
for (int i = 0; i < questionCount; i++) {
    [questionIndices addObject:@(i)];
}
// shuffle
for (int i = questionCount - 1; i > 0; --i) {
    [questionIndices exchangeObjectAtIndex: i
        withObjectAtIndex: arc4random_uniform((uint32_t)i + 1)];
}
// Simulate asking all questions
for (int i = 0; i < questionCount; i++) {
    NSLog(@"questionIndex: %i", [questionIndices[i] intValue]);
}


NSLog output:
questionIndex: 6
questionIndex: 2
questionIndex: 4
questionIndex: 8
questionIndex: 3
questionIndex: 0
questionIndex: 1
questionIndex: 9
questionIndex: 7
questionIndex: 5

附录

洗牌后打印实际文本的示例

// Setup
NSMutableArray *question = [NSMutableArray arrayWithObjects:
    @"Q0 text", @"Q1 text", @"Q2 text", @"Q3 text", @"Q4 text",
    @"Q5 text", @"Q6 text", @"Q7 text", @"Q8 text", @"Q9 text", nil];
// shuffle
for (int i = (int)[question count] - 1; i > 0; --i) {
    [question exchangeObjectAtIndex: i
        withObjectAtIndex: arc4random_uniform((uint32_t)i + 1)];
}
// Simulate asking all questions
for (int i = 0; i < [question count]; i++) {
    printf("%s\n", [question[i] UTF8String]);
}

Sample output:
Q9 text
Q5 text
Q6 text
Q4 text
Q1 text
Q8 text
Q3 text
Q0 text
Q7 text
Q2 text
于 2013-11-09T22:22:22.477 回答
1

这个想法是使用每个问题一次,直到使用完所有问题。

示例代码。请注意,questionIndex 不会重复。

// Setup
int questionCount = 10; // real number of questions
NSMutableArray *questionIndexes = [NSMutableArray array];
for (int i=0; i<questionCount; i++)
    [questionIndexes addObject:@(i)];

// Simulate asking all questions
while (questionIndexes.count) {
    // For each round 
    unsigned long arrayIndex = arc4random_uniform((uint32_t)questionIndexes.count);
    int questionIndex = [questionIndexes[arrayIndex] intValue];
    [questionIndexes removeObjectAtIndex:arrayIndex];
    NSLog(@"arrayIndex: %lu, questionIndex: %i", arrayIndex, questionIndex);
}

NSLog 输出:
arrayIndex: 9, questionIndex: 9
arrayIndex: 5, questionIndex: 5
arrayIndex: 5, questionIndex: 6
arrayIndex: 3, questionIndex: 3
arrayIndex: 3, questionIndex: 4
arrayIndex: 4, questionIndex: 8
arrayIndex: 2, questionIndex :2
数组索引:0,问题索引:0
数组索引:1,问题索引:7
数组索引:0,问题索引:1

于 2013-11-09T21:22:07.283 回答
0

任何随机生成器实际上都是伪随机的。默认情况下,它从相同的初始值开始。要使其“真正随机”,您应该为每次运行提供唯一的起始值,即“盐”。作为一种最简单的方法,您可以使用 [NSDate timeIntervalSinceReferenceDate]。

于 2013-11-09T19:29:57.793 回答
0

将您的问题放入一个数组中,并将随机数放入objectWithIndex. NSMutableArray然后从数组中删除问题。Whenever a index is chosen, but there is not a question anymore, try it again.

于 2013-11-09T19:34:28.537 回答