真随机Xcode [英] True Random Xcode

查看:109
本文介绍了真随机Xcode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个测验应用。当用户启动测验时,随机问题就会出现在测验应用中。问题是,它不是随机的。它确实显示随机问题,但问题重复。我想确保他们不要重复到最后!我的代码是:

I'm currently making a quiz app. When a user starts the quiz random questions show up like you would expect from a quiz app. The problem is, it is not quite random. It does show random questions, but the questions repeat. I wanted to make sure they do not repeat until the end! My code is :

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

        break;

    case 1:
        break;

(...)

是否有更好的方法做到了吗?一种不重复问题的方法?非常感谢你!

Isn't there a better way to do it? A way to just not repeat the questions? Thank you so much!

推荐答案

A shuffle 可能是您的最佳解决方案:

A shuffle may be your best solution:

// 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

ADDENDUM

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

Example with actual text being printed after shuffling

// 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

这篇关于真随机Xcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆