0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bharat
  • 2,987
  • 2
  • 32
  • 48
  • 3
    Just repeat the process until you have three different numbers. – Thilo Aug 21 '12 at 06:58
  • possible duplicate of [iOS: How do I generate 8 unique random integers?](http://stackoverflow.com/questions/6153550/ios-how-do-i-generate-8-unique-random-integers) – Thilo Aug 21 '12 at 07:00
  • yes i repeat it for three times, you say i have to check these numbers in if()? – Bharat Aug 21 '12 at 07:00
  • check out the answers to the other question I linked to. Option one: mark what you've got and repeat. Option two: shuffle an array 0..25 and take the first 3. – Thilo Aug 21 '12 at 07:02
  • @Thilo Its generate 3 unique numbers for me,now i've to choose one number randomly from the three numbers generated. any idea? – Bharat Aug 21 '12 at 08:40

3 Answers3

1

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;
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Its generate 3 unique numbers for me,now i've to choose one number randomly from the three numbers generated. any idea? – Bharat Aug 21 '12 at 08:42
  • @Bharat Generate the index into `numbers[]` using `arc4random_uniform()` and then simply use `numbers[index]`. – trojanfoe Aug 22 '12 at 08:10
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);
}
0

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

}
iSankha007
  • 385
  • 15
  • 21