随机不是随机的不是

2023-09-02 10:41:30 作者:冫京

我使用随机生成的随机数序列。我构成随机对象只是一次,然后在循环产生随机值(其中的300)的内部。现在的问题是,一旦我得到的所有的价值观和做一个排序上他们,我知道有些人是平等的和/或顺序:我生成的数字从0到50000

I am using Random to generate a sequence of random number. I am constructing the random object just once and then inside the loop generating the random values (300 of them). The problem is that once I get all the values and do a sort on them I realize that some of them are equal and/or sequential: I am generating numbers from 0 to 50000.

这是我的脚本:

Random rnd = new Random();
for (int n=0; n < 300; n++)
{
    int RndNumber = rnd.Next(0, 50000);
    System.Threading.Thread.Sleep(3);
}

谁能对为什么发生这种情况的线索,以及如何改善这使其更随机的?

Can someone have a clue on why this is happening, and how can I improve this to make it more random?

推荐答案

作为的为什么的你看到偶尔重复,的贾森的回答是正确的。

As an explanation of why you're seeing the occasional duplicate, Jason's answer is right on.

如果你的需要的是300不同的随机数,那么这样的事情?

If what you want is 300 distinct random numbers, what about something like this?

static IEnumerable<int> GetRandoms(int min, int max)
{
    var rand = new Random();
    while (true)
    {
        yield return rand.Next(min, max);
    }
}

var distinctRandoms = GetRandoms(0, 50000).Distinct().Take(300);