ios - 真正的随机 Xcode

标签 ios iphone xcode random arc4random

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

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/

相关文章:

c 在 xcode : Redeclaration of function must have the overloadable attribute error

ios - 在 SWIFT 中为 iOS 开发解析 json 的问题

cocoa - Xcode:是否有位置/标志来阻止类编译?

ios - ios 9 模拟器中的 mapView 是空白的

ios - 如何在 Vuforia 增强现实 iOS SDK 中使用 .obj 和 .mtl 文件加载 3d 模型

iphone - 用数据填充实体后创建核心数据关系

iphone - UILabel 重新缩放和光栅化时的图像质量问题

swift - 快速使用委托(delegate)将字符串从一个 View Controller 发送到另一个 View Controller

ios - 只有 UIButton 的中心是可点击的

ios - FTP 上传后未获得成功回调