随机不是随机的 [英] Random not that random

查看:171
本文介绍了随机不是随机的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用随机生成的随机数序列。我构成随机对象只是一次,然后在循环产生随机值(其中的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);

这篇关于随机不是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆