“new Random(x)” always generates the same numbers?

2019-02-25 00:39发布

问题:

This question already has an answer here:

  • Random number generator only generating one random number 9 answers

I am trying to get a unique random number but i always get the same number every time i run the code. i will get 14 first then 6 but my list for holding all the used numbers doesn't seem to work.adding the 14 manually works but when i add randInt it doesn't work.

const int numCards = 32;
        List<int> usedCards = new List<int>();
        int randInt = 0;
        Random rand = new Random(numCards);
        usedCards.Add(14);
        do
        {

            randInt = rand.Next(0, numCards);
            MessageBox.Show(randInt.ToString(), "End Game", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        while (usedCards.Contains(randInt));

        usedCards.Add(randInt);

回答1:

Replace:

Random rand = new Random(numCards);

with

Random rand = new Random();

Supplying a fixed seed value (numCards always has the same value) in the Random constructor call will result in a predictable, reproducible sequence which is always the same for the same seed value, just like this (not quite but still the point is valid):

For example using a fixed seed of 1 and drawing 10 numbers ranging from 0 to 100, on my machine always produces the sequence

24,11,46,77,65,43,35,94,10,64

Using no seed value on the other hand, the sequence becomes unpredictable.

Without a seed value passed in, Random will generate a new seed value based on the current time, that's what you want to get a new sequence of random numbers - provided you don't initialize it again in fast order, that's why you should re-use Random instances instead of re-creating them every time.



回答2:

Random Class

If you specify a seed value to the Random class constructor, it will generate the same sequence every time. The algorithm to produce the random number sequence is deterministic.

If you use the constructor without parameters, the Random object will use a seed value on the current time, so each Random object instantiated using this constructor will have a different sequence of random numbers as long as the time seed value is different which is likely.

You can still get the same sequence of numbers from two different Random objects if they are initialized very close in time to each other.

Random Constructor



标签: c# random