0

我正在尝试生成 0 到 25 之间的 3 个随机数。我用arc4random_uniform(25)它来生成 3 个随机数。但问题是有时我得到两个甚至所有三个数字都是相同的,但我需要 3 个唯一数字。

4

3 回答 3

1

正如@Thilo 所说,您必须检查它们是随机的,如果不是,则重复:

// This assumes you don't want 0 picked
u_int32_t numbers[3] = { 0, 0, 0 };
for (unsigned i = 0; i < 3; i++)
{
    BOOL found = NO;
    u_int32_t number;
    do
    {
        number = arc4random_uniform(25);
        if (i > 0)
            for (unsigned j = 0; j < i - 1 && !found; j++)
                found = numbers[j] == number;
    }
    while (!found);
    numbers[i] = number;
}
于 2012-08-21T07:09:41.137 回答
1
int checker[3];
for(int i = 0 ; i < 3 ; i++){
    checker[i] = 0;
}
for(int i = 0 ; i < 3 ; i++){
    random = arc4random() % 3;
    while(checker[random] == 1){
        random = arc4random() % 20;
    }
    checker[random] = 1;
    NSLog(@"random number %d", random);
}
于 2013-12-04T09:26:29.833 回答
0

我正在通过以下方式生成一个唯一随机数数组:

-(void)generateRandomUniqueNumberThree{
    NSMutableArray *unqArray=[[NSMutableArray alloc] init];
    int randNum = arc4random() % (25);
    int counter=0;
    while (counter<3) {
        if (![unqArray containsObject:[NSNumber numberWithInt:randNum]]) {
            [unqArray addObject:[NSNumber numberWithInt:randNum]];
            counter++;
        }else{
            randNum = arc4random() % (25);
        }

    }
    NSLog(@"UNIQUE ARRAY %@",unqArray);

}
于 2014-11-22T17:38:41.973 回答