Как использовать цикл «пока» для предотвращения того же числа в случайном числе в XCode? - PullRequest
0 голосов
/ 23 июля 2011

Я хочу, чтобы он генерировал другое случайное число.Как использовать оператор «Пока»?

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

Ответы [ 2 ]

1 голос
/ 23 июля 2011

Может быть, что-то вроде этого. Он зацикливается, пока не найдет число, которого нет в массиве.

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

Если вам нужно много случайных чисел, вы можете поместить все это в другой цикл, который выполняется столько раз, сколько вам нужно отдельных чисел.

0 голосов
/ 23 июля 2011

NSMutableSet не позволяет повторять.

    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.
...