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
NOTE, I dont recommend this :). Here's a "oneliner" as well:
You could also use a dataTable storing each random value, then simply perform the random method while != values in the dataColumn
Check this ready-to-use method: Give in a range & count of number you want to get.
randomNumber function return unqiue integer value between 0 to 100000
You might try shuffling an array of possible ints if your range is only 0 through 9. This adds the benefit of avoiding any conflicts in the number generation.
Random.Next
doesn't guarntee 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 ofint
and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like: