Bharat
Bharat

Reputation: 3007

Generating 3 unique random numbers in Objective-C?

I'm trying to generate 3 random numbers between 0 to 25. I used arc4random_uniform(25) for this and it generate 3 random numbers.but problem is that some time I get two or even all three numbers are same, but I require 3 unique numbers.

Upvotes: 0

Views: 2095

Answers (3)

iSankha007
iSankha007

Reputation: 395

I am generating an Array of unique Random Number in the following way:

-(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);

}

Upvotes: 0

Chan Kai Long
Chan Kai Long

Reputation: 51

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);
}

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

As @Thilo said you have to check they are random and repeat if they are not:

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

Upvotes: 1

Related Questions