簡體   English   中英

我如何才能使隨機數不再在數組中重復?

[英]How can I make random numbers that never repeat in array?

listBox1.Items.Clear();
int[] sayısal = new int[6];
Random rastgele = new Random();
for (int i = 0; i < 6; i++)
{
   do
   {
      sayısal = rastgele.Next(1, 50);
   }
   while (listBox1.Items.IndexOf(sayısal) != -1);
      listBox1.Items.Add(sayısal);
}

當我這樣做時,我會遇到一個錯誤

“無法將類型'int'隱式轉換為'int []'”

"sayısal = rastgele.Next(1, 50);" 我該怎么辦?

您可以生成序列1..50並對其進行混洗(即按隨機值排序):

Random rastgele = new Random();
int[] sayısal = Enumerable.Range(1, 50) // generate sequence
                          .OrderBy(i => rastgele.Next()) // shuffle
                          .Take(6) // if you need only 6 numbers
                          .ToArray(); // convert to array

您的代碼不起作用,因為您試圖將生成的項目分配給數組變量。

sayısal = rastgele.Next(1, 50);

應該改為:

do {
   sayısal[i] = rastgele.Next(1, 50);
} while(listBox1.Items.IndexOf(sayısal[i]) != -1);

正如我已經在評論中指出的那樣,最好將UI邏輯和數組生成分開。

// generate array (optionally move to separate method)
int itemsCount = 6;
int[] items = new int[itemsCount]; // consider to use List<int>
Random random = new Random();
int item;

for(int i = 0; i < itemsCount; i++)
{
   do {
      item = random.Next(1, 50);
   } while(Array.IndexOf(items, item) >= 0);

   items[i] = item;
}

// display generated items
listBox1.Items.Clear();
for(int i = 0; i < items.Length; i++) // or use foreach
    listBox1.Items.Add(items[i]);

因為Random.Next方法返回一個int ,而不是int[] int[]int沒有隱式的主張。

Return Value
Type: System.Int32
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

如果要填充數組,可以使用Enumerable.Range提到的lazyberezovsky一樣。

此方法采用整數數組並對它們進行隨機排序。 因此,用循環填充數組,然后使用它對數組進行隨機排序。 您應該記下其他人中的一個,因為他們首先發布了有效答案。 我只是認為另一種方式可以做到這一點。

數量是您希望數組隨機化的次數。 數字越高,數字出現隨機的可能性越高。

    private Random random = new Random();

    private int[] randomizeArray(int[] i, int amount)
    {
        int L = i.Length - 1;
        int c = 0;
        int r = random.Next(amount);
        int prev = 0;
        int current = 0;
        int temp;

        while (c < r)
        {
            current = random.Next(0, L);
            if (current != prev)
            {
                temp = i[prev];
                i[prev] = i[current];
                i[current] = temp;
                c++;
            }
        }
        return i;
    }

選擇數據結構和算法時要小心,選擇錯誤的數據結構和算法,然后您會得到O(n ^ 2)。 恕我直言,合理的解決方案是鍵入哈希表(即字典),它會給你O(n):

Random rnd = new Random();              
        var numbers = Enumerable
            .Range(1, 1000000)
            .Aggregate(new Dictionary<int, int>(), (a, b) => {
                int val;
                do {val = rnd.Next();} while (a.ContainsKey(val));
                a.Add(val, val);
                return a;
            })
            .Values
            .ToArray();

仍然不理想,因為性能取決於數組的大小顯着小於可用數字的集合,並且無法檢測到何時不滿足此條件(或更糟糕的是,當條件更大時,算法將進入無限循環)。

暫無
暫無

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

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