我目前正在制作一个测验应用程序。当用户开始测验时,随机问题会出现,就像您对测验应用程序所期望的那样。问题是,它不是很随机。它确实会显示随机问题,但问题会重复出现。我想确保他们不会重复直到最后!我的代码是:
int Questions = arc4random_uniform(142);
switch (Questions) {
case 0:
break;
case 1:
break;
(...)
有没有更好的方法呢?一种不重复问题的方法?非常感谢!
最佳答案
A shuffle可能是您最好的解决方案:
// 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
关于ios - 真正的随机 Xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19882080/