簡體   English   中英

C中非重復數字的數組?

[英]array of non repeating numbers in C?

到目前為止,我有一組來自1-49的六個隨機數,但有些重復,例如,12 15 43 43 22 15是否可以解決這個問題?

到目前為止我有......

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

任何反饋都會很棒,謝謝

你可以簡單地扔掉重復的東西。

另一個選擇是創建一個數字1-49的數組, 將它們改組,然后取第一個6。

您需要添加一個單獨的循環,該循環從0 (包括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);
   }
}

在ideone上演示。

rand函數不知道它以前的輸出,所以你可以在將它保存到數組之前進行檢查

如果你得到第一個隨機數為x ,找到第二個隨機數作為隨機的random(1 to x-1)random(x+1 to n) 繼續這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM