True Random Xcode

后端 未结 4 985
耶瑟儿~
耶瑟儿~ 2021-01-26 02:01

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 sho

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 02:22

    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
    

提交回复
热议问题