如何使c#随机数重复

How to make c# Random Numbers repeat

我正在尝试生成随机数组来测试我的家庭作业。 问题是生成的数字总是唯一的,我时不时需要一些重复的数字。

这是我想出的代码:

static int[] RandomIntArray()
{
    Random rnd = new Random();
    Console.Write("Enter array Length: ");
    int n = int.Parse(Console.ReadLine());
    int[] arr = new int[n];

    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = rnd.Next(short.MinValue, short.MaxValue);
    }

    return arr;
}

您可以为随机数生成器播种,因此它始终会生成相同的随机序列:

Random rnd = new Random(1/* Any seed value you want in here */);

如果你想强制重复一些数字,你可以这样做:

static int[] RandomIntArray()
{
    Random rnd = new Random();
    Console.Write("Enter array Length: ");
    int n = int.Parse(Console.ReadLine());
    int[] arr = new int[n];

    for (int i = 0; i < arr.Length; i++)
    {
        if(i > 0 && rnd.Next(10) == 1) // a 1 in 10 chance of a dupe
        {
            arr[i] = arr[i-1]; 
        }
        else
            arr[i] = rnd.Next(short.MinValue, short.MaxValue);
    }

    return arr;
}

您希望重复数字的频率将决定您使用何种方法。您始终可以将获得的随机数四舍五入到最接近的 10、100,直到 "bins" 足够大以至于 "bins" 可以根据需要频繁出现。这类似于@DLeh 建议的缩小范围,但它允许您将生成的数字分布在更大的范围内。

如果你用相同的种子初始化随机数,你将一直得到相同的数字序列

Random rnd1 = new Random(5);
Random rnd2 = new Random(5);

for(var i=0;i<10; i++){
    Console.WriteLine(rnd1.Next() + ", " + rnd2.Next());
}

如果您希望数字偶尔重复一次,请缩小范围。它们更有可能导致重复。

    arr[i] = rnd.Next(0, 10);