2011-07-23 32 views
0

我希望它不斷生成不同的隨機數。如何使用While語句?如何使用While循環來防止在Xcode中的隨機數相同的數字?

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

回答

1

也許是這樣的。它循環直到找到一個不在數組中的數字。

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

謝謝大家。所有的答案都很好。我無法檢查所有這些。我使用'removeallobjects'來防止無限循環。 – Noob

0

NSMutableSet不允許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. 
相關問題