-1

我正在尝试制作一个测验应用程序,但我是 IOS 新手。我想从一个特定问题的 6 个错误答案的数组中得到 3 个错误答案,每个问题都有 1 个正确答案。我想随机化错误每次显示问题时的选项。因此,每次显示问题时,应用程序都会从​​数组中选择 3 个错误选项和 1 个正确答案。我该如何编码?如果您能帮助我,我会很高兴。

谢谢..

{
    int counted = [theOptions count];

    int i;



    NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:counted];

    for (i=0; i<counted; i++) [indexes addObject:[NSNumber numberWithInt:i]];
    NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:counted];
    while ([indexes count])
    {
        int index = rand()%[indexes count];
        [shuffle addObject:[indexes objectAtIndex:index]];
        [indexes removeObjectAtIndex:index];
    }

    NSMutableArray* shuffledOptions = [[NSMutableArray alloc] initWithCapacity:4];
    for (int i=0; i<counted; i++)
    {
        int randomIndex = [[shuffle objectAtIndex:i] intValue];
        [shuffledOptions addObject:[theOptions objectAtIndex:randomIndex]];
        UIButton* optionButton = [_optionsButtonsArray objectAtIndex:i];
        optionButton.tag = randomIndex;

    }
    return shuffledOptions;

}

return theOptions;}
4

2 回答 2

0

如果您有一个包含 6 个错误答案的数组,并且想要随机选择其中三个

NSArray *answers = [NSArray arrayWithObjects:@"Wrong #1", @"Wrong #2", @"Wrong #3", @"Wrong #4", @"Wrong #5", @"Wrong #6"];
NSMutableArray *output = [[NSMutableArray alloc] init];
int r;
while (output.count < 3) {
r = arc4random_uniform(5);
if (![output containsObject:[answers objectAtIndex:r]]) {
[output addObject:[answers objectAtIndex:r]];
}}
于 2013-08-14T18:47:11.853 回答
0

最简单的方法是选择 0-5 之间的随机数,然后选择另一个随机数。如果下一个是第一个的副本,请重复上一步。再做一次,你现在有三个从 0 到 5 的唯一随机数。

更聪明的方法是将数字 1-5 存储在一个数组中。打乱数组,然后返回前三个索引。

祝你好运。

于 2013-08-14T18:50:47.430 回答