简体   繁体   English

如何检查阵列中的重复项?

[英]How do I check for duplicates in my array?

How do I store a random number into my array, but only if there is not a duplicate already inside the array? 如何将随机数存储到数组中,但前提是数组中没有重复数? My code below still inputs a duplicate number. 我下面的代码仍然输入重复的数字。

        Random rand = new Random();
        int[] lotto = new int [6];

        for (int i = 0; i < lotto.Length; i++)
        {
            int temp = rand.Next(1, 10);
            while (!(lotto.Contains(temp)))//While my lotto array doesn't contain a duplicate
            {
                lotto[i] = rand.Next(1, 10);//Add a new number into the array
            }
            Console.WriteLine(lotto[i]+1);
        }

Try this: 尝试这个:

Random rand = new Random();
int[] lotto = new int[6];

for (int i = 0; i < lotto.Length; i++)
{
    int temp = rand.Next(1, 10);

    // Loop until array doesn't contain temp
    while (lotto.Contains(temp))
    {
        temp = rand.Next(1, 10);
    }

    lotto[i] = temp;
    Console.WriteLine(lotto[i] + 1);
}

This way the code keeps generating a number until it finds one that isn't in the array, assigns it and moves on. 这样,代码会不断生成一个数字,直到找到一个不在数组中的数字,然后分配它并继续前进。

There are a lot of ways to 'shuffle' an array, but hopefully this clears up the issue you were having with your code. 有很多方法可以“随机”排列数组,但是希望这可以解决您的代码问题。

What you really want is to shuffle the numbers from 1 to 9 (at least that's what your example is implying) and then take the first 6 elements. 真正想要的是将数字从1改到9(至少这是您的示例所暗示的意思),然后采用前6个元素。 Checking for duplicates is adding unnecessary indeterminism and really is not needed if you have a shuffle. 检查重复项会增加不必要的不​​确定性,如果您需要改组,则实际上不需要。

Eg take this accepted answer for a Fisher-Yates shuffle and then take the first 6 elements for lotto . 例如,将这个公认的答案用于Fisher-Yates混洗 ,然后将前6个元素用于lotto

This would then look like this: 然后将如下所示:

lotto = Enumerable.Range(1,9)
                  .Shuffle()
                  .Take(6)
                  .ToArray();

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

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