"new Random(x)" always generates the same numbers?

c#, random

Solution

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.

Problem

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); ```

Original source

Related problems