2014-07-07 34 views
-3

這是我從1-99生成隨機數的代碼,但它每次只生成一組相同的數字(15個數字)。我將這些數字存儲在NSArray中,並正確獲取NSLog的輸出。沒關係,但是當我將這種隨機方法稱爲隨機數時,我需要不同的隨機數而不需要重複編號。任何人都可以幫助我嗎?如何在Objective-C中從1-99範圍內生成隨機數?

-(void) randoms 
{ 

    myset=[[NSArray alloc]init]; 
    int D[20]; 
    BOOL flag; 
    for (int i=0; i<15; i++) 
    { 
     int randum= random()%100; 
     flag= true; 
     int size= (sizeof D); 

     for (int x=0; x<size; x++) 
     { 
      if (randum == D[x]) 
      { 
       i--; 
       flag= false; 
       break; 
      } 
     } 

     if (flag) D[i]=randum; 

    } 
    for (int j=0; j<15; j++) 
     { 
     myset=[myset arrayByAddingObject:[NSNumber numberWithInt:D[j]]]; 
     } 

    NSLog(@"first set..%@",myset.description); 
} 
+0

調用它給這一個嘗試http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective- c – Anupdas

+0

這真是令人煩惱。對代碼有很好的解釋,並且這個問題已經關閉了。我會將它添加到博客,並在可以時爲您提供鏈接。 – Popeye

+0

雖然有一個元素是重複的 - 生成唯一的隨機數,也有將隨機數放在一個集合中的元素,所以我提名重新開放 – Paulw11

回答

0

開始你arc4random

srand(time(NULL)); 
+0

http://stackoverflow.com/questions/8410571/non-repeating-random-numbers-in-iphone嘗試上面的鏈接... – Sri

+0

你甚至知道那是什麼嗎?如果是這樣,請添加一個解釋,它是什麼和做什麼,對於那些不是 – Popeye

+0

它種子的rand()使用的僞隨機數發生器..更多的細節檢查此鏈接: - http://www.cplusplus .com/reference/clibrary/cstdlib/srand/ – Sri

2

你必須在使用前將種子生成器之前嘗試這個命令。如果您想跳過播種,可以使用arc4random_uniform()。這是一種不同的算法,並自行處理播種過程。除此之外,你可以在你的代碼中使用它幾乎和你使用的random()一樣。你只需要指定上限作爲參數,而不是使用模:

-(void) randoms 
{ 

    myset=[[NSArray alloc]init]; 
    int D[20]; 
    BOOL flag; 
    for (int i=0; i<15; i++) 
    { 
     int randum= arc4random_uniform(100); 
     flag= true; 
     int size= (sizeof D); 

     for (int x=0; x<size; x++) 
     { 
      if (randum == D[x]) 
      { 
       i--; 
       flag= false; 
       break; 
      } 
     } 

     if (flag) D[i]=randum; 

    } 
    for (int j=0; j<15; j++) 
     { 
     myset=[myset arrayByAddingObject:[NSNumber numberWithInt:D[j]]]; 
     } 

    NSLog(@"first set..%@",myset.description); 
} 
+0

[arc4random_uniform()](http://stackoverflow.com/a/7082580/169346)是要走的路 – JeremyP

+0

謝謝,我不知道arc4random_uniform()。編輯答案,我將來可能會使用它,而不是arc4random()。 – Vingdoloras

+0

是啊,,,偉大偉大的工作由你完成..對我的輝煌援助。 – ArghyaM

0

如果我正確理解你想要的含1-99之間15張隨機數的集合。您可以使用以下方法:

- (NSSet *)randomSetOfSize:(int)size lowerBound:(int)lowerBound upperBound:(int)upperBound { 
    NSMutableSet *randomSet=[NSMutableSet new]; 
    while (randomSet.count <size) { 
     int randomInt=arc4random_uniform(upperBound-lowerBound)+lowerBound; 
     NSNumber *randomNumber=[NSNumber numberWithInt:randomInt]; 
     [randomSet addObject:randomNumber]; 
    } 

    return randomSet; 
} 

NSSet *myRandomSet=[self randomSetOfSize:14 lowerBound:1 upperBound:99]; 
相關問題