I’ve searched for a while and been struggling to find this, I’m trying to generate several random, unique numbers is C#. I’m using System.Random, and I’m using a DateTime.Now.Ticks seed:
public Random a = new Random(DateTime.Now.Ticks.GetHashCode());
private void NewNumber()
{
MyNumber = a.Next(0, 10);
}
I’m calling NewNumber() regularly, but the problem is I often get repeated numbers. Some people suggested because I was declaring the random every time I did it, it would not produce a random number, so I put the declaration outside my function. Any suggestions or better ways than using System.Random ? Thank you
Random.Nextdoesn’t guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list ofintand insert random numbers in the list after checking if it doesn’t contain the duplicate. Something like: