When I declare Random inside my loop in C#, it giv

2019-08-05 20:45发布

This question already has an answer here:

I'm creating a deck of cards. When I try to shuffle, I am getting some weirdness.

The constructor before calling my program goes through the following loop (pseudo code,inclusive)-

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

This is the simplified form,anyway. Basically a card with a number and a suit is generated. Now the problem code (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;
}

This gives me semi-predictable output - i.e. the following:

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

Near the end it seems to break the pattern, but I'm not sure why. Running it again gives me different, but non-random, outputs.

However, if I remove the random declaration to OUTSIDE the loop -

    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;
    }

I get much more random seeming numbers, in this case -

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

This difference seems to disappear when I publish the code from Visual Studio and run the outputted program. I'm confused as to what's going on. Since I have 4 cores, is this distributing the process to 4 cores at the same millisecond, thereby using the same number as its seed? That wouldn't make sense as to why it's working when I publish the code, though...

1条回答
该账号已被封号
2楼-- · 2019-08-05 21:35

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,

By having the declaration in the loop you are effectively calling the constructor with the same value over and over again - hence you are getting the same numbers out.

Random Class

查看更多
登录 后发表回答