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);
Replace:
with
Supplying a fixed seed value (
numCardsalways has the same value) in theRandomconstructor 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
1and drawing 10 numbers ranging from 0 to 100, on my machine always produces the sequenceUsing no seed value on the other hand, the sequence becomes unpredictable.
Without a seed value passed in,
Randomwill 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-useRandominstances instead of re-creating them every time.