在Objective-C中生成3个唯一的随机数?

时间:2012-08-21 06:56:01

标签: ios objective-c random

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

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);
}

答案 2 :(得分: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);

}