Home >Backend Development >C++ >How Can I Generate Unique Random Numbers in C#?
Generating unique random numbers in C#
Question:
C# developers often face the challenge of generating unique random numbers. Even if you use System.Random and DateTime.Now.Ticks as seeds, you may encounter problems with duplicate numbers. Can you suggest an alternative way to solve this problem?
Answer:
While Random.Next does not guarantee uniqueness, a simple solution is to maintain a list of generated numbers. The algorithm below demonstrates how to achieve this:
<code class="language-csharp">public Random a = new Random(); private List<int> randomList = new List<int>(); int MyNumber = 0; private void NewNumber() { MyNumber = a.Next(0, 10); if (!randomList.Contains(MyNumber)) randomList.Add(MyNumber); }</code>
This code initializes a Random instance (no GetHashCode call required as it is done internally by default) and a list to store the generated numbers. The NewNumber function generates a random number between 0 and 9. If the number is not in the list, it is added to the list, thus ensuring the uniqueness of the number within the given range.
The above is the detailed content of How Can I Generate Unique Random Numbers in C#?. For more information, please follow other related articles on the PHP Chinese website!