c# - 当我在 C# 的循环内声明 Random 时,它会给我非随机数 - 在我的循环外声明它会给我随机数。为什么?

标签 c# visual-studio random

<分区>

我正在制作一副纸牌。当我尝试洗牌时,我感到有些奇怪。

调用我的程序之前的构造函数经过了如下循环(伪代码,含)-

for i in (0,13):
   for j in (0,3):
      new Card(i,j)

无论如何,这是简化的形式。基本上会生成一张带有数字和花色的卡片。现在问题代码(C#):

private void Shuffle()
{
    List<Card> newList = new List<Card>();
    while (cards.Count > 0)
    {
        Random r = new Random();
        int next = r.Next(0,cards.Count);
        Console.WriteLine(next);
        Card cur = cards.ElementAt(next);
        newList.Add(cur);
        cards.Remove(cur);
    }
    this.cards = newList;
}

这给了我半可预测的输出 - 即以下内容:

18 18 18 17 17 17 16 16 15 15 15 14 14 14 13 13 13 12 12 12 11 11 11 10 10 10 9 9 9 8个 8个 8个 7 7 7 6个 6个 6个 5个 5个 5个 4个 4个 3个 3个 3个 1个 5个 4个 3个 2个 2个 1个 0

接近尾声它似乎打破了模式,但我不确定为什么。再次运行它会得到不同但非随机的输出。

但是,如果我删除循环外的随机声明 -

    private void Shuffle()
    {
        List<Card> newList = new List<Card>();
        Random r = new Random(); /** THE ONLY DIFFERENT LINE **/
        while (cards.Count > 0)
        {
            int next = r.Next(0,cards.Count);
            Console.WriteLine(next);
            Card cur = cards.ElementAt(next);
            newList.Add(cur);
            cards.Remove(cur);
        }
        this.cards = newList;
    }

在这种情况下,我得到了更多看似随机的数字 -

19,28,21,2,16,20,33,26,7,36,31,33,33,26,34,4,18,20,13,27,16,11,18,22 ,18,21,21,8,22,12,6,17,2,17,0,11,2,14,9,0,8,10,1,7,4,1,0,0,2 ,1,0,0

当我从 Visual Studio 发布代码并运行输出程序时,这种差异似乎消失了。我对发生了什么感到困惑。由于我有 4 个核心,这是否会在同一毫秒内将进程分配给 4 个核心,从而使用相同的数字作为其种子?但是,当我发布代码时,这对于为什么它能正常工作是没有意义的......

最佳答案

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value,

通过在循环中声明,您可以有效地一遍又一遍地调用具有相同值的构造函数 - 因此您得到相同的数字。

Random Class

关于c# - 当我在 C# 的循环内声明 Random 时,它会给我非随机数 - 在我的循环外声明它会给我随机数。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18204140/

相关文章:

c# - 信箱不可用。服务器响应是 : relay not permitted

c# - 如何解决 'NReco.VideoConverter.FFMpegException' 错误?

c# - 未指定或无效的 Oracle UDTs 自定义类型映射

c# - 使用从软件应用程序保存/另存为将文件上传到网站

visual-studio - 从 Visual Studio 2022(MAUI、Xamarin)到 macOS 的连接失败

c++ - 使用C++和Visual Studio调试是否有办法在超出数组或内存分配的界限时始终抛出异常?

random - 数组长度范围内的 Ada 随机整数

java - 经过多少次迭代后,SecureRandom 将生成给定范围内的所有数字?

visual-studio - 有人找到了适用于 Visual Studio 的 PowerShell 语法突出显示或 IntelliSense 插件吗?

python : How to use random sample when we don't need duplicates random sample