Noob
Noob

Reputation: 55

How to use While loop to prevent the same number in random number in Xcode?

I want it keeps generating different random number. How to use While statement?

int randomnumber = (arc4random() % 188)+1; 

if ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
    NSLog(@"Yes, they are the same");
    randomnumber = (arc4random() % 188)+1;
}
else
{
    NSLog(@"No, they are not the same");
        }
[myArray addObject:[NSNumber numberWithInt:randomnumber]];

Upvotes: 0

Views: 2171

Answers (2)

NSMutableSet wont allow dublicate.

    NSMutableSet * numberWithSet = [[NSMutableSet alloc]initWithCapacity:20]

    while ([numberWithSet count] < 20 ) {

        NSNumber * randomNumber = [NSNumber numberWithInt:(arc4random() % 23 + 1)];

        [numberWithSet addObject:randomNumber];

    }

        NSLog(@"numberWithSet : %@ \n\n",numberWithSet);

    [numberWithSet release];

    `arc4random() % 22 + 1` will give you numbers between 1 and 22 including both of them but not 23.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477040

Maybe something like this. It loops until it finds a number that's not in the array.

int randomnumber = (arc4random() % 188)+1; 

while ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
    NSLog(@"Yes, they are the same");
    randomnumber = (arc4random() % 188)+1;
}

[myArray addObject:[NSNumber numberWithInt:randomnumber]];

If you need lots of random numbers, you can put the whole thing into another loop that runs for as many rounds as you need distinct numbers.

Upvotes: 1

Related Questions