简体   繁体   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);
}

When I did like this, I take an error that calls 当我这样做时,我会遇到一个错误

"Cannot implicitly convert type 'int' to 'int[]' " “无法将类型'int'隐式转换为'int []'”

in line "sayısal = rastgele.Next(1, 50);" "sayısal = rastgele.Next(1, 50);" . What can I do for it? 我该怎么办?

You can generate sequence 1..50 and shuffle it (ie sort by random value): 您可以生成序列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

Your code is not working, because you are trying to assign generated item to array variable. 您的代码不起作用,因为您试图将生成的项目分配给数组变量。

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

It should be instead: 应该改为:

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

As I already pointed in comments, it's better to separate UI logic and array generation. 正如我已经在评论中指出的那样,最好将UI逻辑和数组生成分开。 Ie

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

Because Random.Next method returns an int , not int[] . 因为Random.Next方法返回一个int ,而不是int[] And there is no implicit conersation from int[] to 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.

If you want to fill your array, you can use Enumerable.Range like lazyberezovsky mentioned . 如果要填充数组,可以使用Enumerable.Range提到的lazyberezovsky一样。

This method takes an integer array and randomly sorts them. 此方法采用整数数组并对它们进行随机排序。 So fill an array with a loop then use this to randomly sort the array. 因此,用循环填充数组,然后使用它对数组进行随机排序。 You should credit one of the others as they were first to post with valid answers. 您应该记下其他人中的一个,因为他们首先发布了有效答案。 I just thought another way to do this would be good. 我只是认为另一种方式可以做到这一点。

amount is the amount of times you want the array to randomize. 数量是您希望数组随机化的次数。 The higher the number the higher the chance of numbers being random. 数字越高,数字出现随机的可能性越高。

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

Be careful in your choice of data structures and algorithms, pick the wrong one and you'll wind up with O(n^2). 选择数据结构和算法时要小心,选择错误的数据结构和算法,然后您会得到O(n ^ 2)。 A reasonable solution IMHO is a typed hash table (ie dictionary) which will give you O(n): 恕我直言,合理的解决方案是键入哈希表(即字典),它会给你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();

Still not ideal though as performance depends on the array size being significantly smaller than the set of available numbers and there's no way to detect when this condition isn't met (or worse yet when it's greater, in which case the algorithm will go into an infinite loop). 仍然不理想,因为性能取决于数组的大小显着小于可用数字的集合,并且无法检测到何时不满足此条件(或更糟糕的是,当条件更大时,算法将进入无限循环)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM