2014-03-19 52 views
1

我有一個從1-49到目前爲止六個隨機數組的數組,但有些重複,例如,12 15 43 43 22 15 是否有解決此問題的方法?C中非重複數組的數組?

到目前爲止,我...

int* get_numbers() 
{ 
     int Array[6], i; 
     printf("\n\n Your numbers are : "); 
     for (i = 0; i < 6; i++) 
     { 
       Array[i] = ((rand() % 49) + 1); 
       printf("%d ",Array[i]); 
     } 
} 

任何反饋將是巨大的,感謝

+0

你試圖解決什麼問題?你需要6個唯一的號碼嗎? – Scott

回答

1

您需要添加一個單獨的循環,從0,包容去,到i,獨家,檢查候選人編號與之前添加到數組中的編號。如果檢查時發現了重複,不增加i,然後嘗試重新生成一個隨機數:

int i = 0; 
while (i != 6) { 
    int candidate = ((rand() % 49) + 1); 
    int ok = 1; // ok will become 0 if a duplicate is found 
    for (int j = 0 ; ok && j != i ; j++) { 
     ok &= (candidate != Array[j]); 
    } 
    if (ok) { 
     Array[i++] = candidate; 
     printf("%d ", candidate); 
    } 
} 

Demo on ideone.

2

你可以簡單地扔掉重複。

另一種選擇是創建數字1-49,shuffle them數組,然後在第一個6

0

蘭特功能並不知道它以前的輸出,所以你可以把你檢查保存之前在陣列中

0

如果您得到第一個隨機數x,請找到第二個隨機數作爲random(1 to x-1)random(x+1 to n)的隨機數。以這種方式繼續。