Reputation: 3007
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
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
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
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