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
To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values.
rand() rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
I'm calling NewNumber() regularly, but the problem is I often get repeated numbers.
Random.Next
doesn'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 of int
and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:
public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode()); // Since similar code is done in default constructor internally public List<int> randomList = new List<int>(); int MyNumber = 0; private void NewNumber() { MyNumber = a.Next(0, 10); if (!randomList.Contains(MyNumber)) randomList.Add(MyNumber); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With