【问题标题】:Check for duplicates in c# [duplicate]在c#中检查重复项[重复]
【发布时间】:2017-09-16 03:16:03
【问题描述】:

我想检查我在 shuffle 方法中传递的数组是否有任何重复项。 我还想生成一个大小为 a.length 的随机数。

问题是我不知道如何检查数组是否有重复,如果有,它会生成另一个数字,直到它与其他数字不同。

public int[] Shuffle(int[] a)
    {

        //check if the array has duplicates
        for (int i = 0; i < a.Length; i++)
        {
            int curValue = random.Next(a.Length);
            if(a.Contains(curValue))
            {
                curValue = random.Next(a.Length);
            }
            else
            {
                a[i] = curValue;
            }
        }

        for (int i = 0; i < a.Length; i++)
        {
            int r = random.Next(a.Length);
            int t = a[r];
            a[r] = a[i];
            a[i] = t;
        }

        return a;
    }

谁能帮帮我?

【问题讨论】:

  • 这似乎是一件奇怪的事情(输入数组是什么?只有它的大小重要吗?E:编辑后使用输入,但以一种奇怪的方式),也是你的洗牌部分以一种偷偷摸摸且难以察觉的方式是错误的。
  • 首先我想用随机数填充我的数组取决于我的array.length。但是我不想重复,然后我想根据数组长度在随机位置随机排列我的数组。有什么建议吗?
  • 了解 Linq 的 .Distinct() 方法。至于所有一起生成随机唯一数字的集合,在 SO 中搜索更多,我在过去看到了很多解决方案
  • 如果你只想要数字 0 .. a.length - 1,你可以用一种简单的方式 (a[i] = i) 将它们放在那里,然后随机播放它们(查找 Knuth shuffle ,真的很容易弄错乱序)
  • 我建议您使用Fisher-Yates shuffle。基本上在集合大小范围内生成一个随机数,从该位置获取值,然后将其从集合中删除,使下次范围变小。重复直到集合为空。

标签: c# random numbers generator


【解决方案1】:

这是一个功能,可以按照我的假设完成您的要求。包括使用 System.Linq 来运行它。我是根据您的文字进行的,因为代码没有让我清楚您的问题。如果您的意思不同,请澄清。

        static int[] Shuffle(int[] a)
    {
        Random rnd = new Random();

        //Remove duplicates from array
        int[] distinct = a.Distinct().ToArray();

        //Add the same amount of unique numbers that have been removed as duplicates
        int len = a.Length - distinct.Length;
        int[] newNumbers = new int[len];
        int i = 0;
        while(i < len)
        {
            newNumbers[i] = rnd.Next(a.Length); //NOTE: here i put in the length of array a, but with an int array this will always resolve in a shuffled array containing all digits from 0 to the length-1 of the array.
            if (!distinct.Contains(newNumbers[i])  && !newNumbers.Take(i).Contains(newNumbers[i]))
            {
                ++i;
            }
        }

        //Randomize the array           
        int[] b = a.OrderBy(x => rnd.Next()).ToArray();

        //Concatenate the two arrays and return it (shuffled numbers and new unique numbers)
        return distinct.Concat(newNumbers).ToArray();
    }

正如我在注释中所说,如果您保留一个整数数组并且只允许添加小于数组长度的新随机替换数,那么您将使用一个从 0 到数组长度的所有数字的随机数组.

由于newNumbers的新数组生成了,你还需要检查新生成的数字是否不在该数组中。

【讨论】:

  • 这真的帮助了我。这实际上帮助我弄清楚了我的问题是什么。
  • 不幸的是,这是一种非常糟糕的方法。
  • 很高兴能提供帮助,如果有帮助,请接受作为答案或投票。 @Harold,当然有更好的方法可以做到这一点,这段代码效率很低,所以如果愿意,请提供更好的实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多