Home >Backend Development >C++ >How to Generate Truly Unique Random Numbers in C#?
Effective way to generate unique random values in C#
Generating unique random numbers is a common requirement in many programming scenarios. However, using the default System.Random
class does not guarantee uniqueness, especially if the scope is small.
Limitations of Random.Next()
TheRandom.Next()
method is not designed to generate unique values within a given range. It generates a random integer within the specified range, and may produce duplicate numbers, especially if the range is small.
Use seed value
Using a seed value, such as DateTime.Now.Ticks.GetHashCode()
, is a common way to improve Random
-like randomness. However, it still doesn't eliminate the possibility of generating duplicate numbers.
Better solution
Instead of relying on Random.Next()
, consider using the following method to generate unique random numbers:
<code class="language-csharp">public class RandomGenerator { private readonly Random _random; private HashSet<int> _uniqueValues; public RandomGenerator() { _random = new Random(); _uniqueValues = new HashSet<int>(); } public int GetUniqueNumber(int min, int max) { int randomNumber; do { randomNumber = _random.Next(min, max); } while (_uniqueValues.Contains(randomNumber)); _uniqueValues.Add(randomNumber); return randomNumber; } }</code>
This method uses HashSet
to store the generated value. The GetUniqueNumber
method repeatedly generates random numbers until a unique value is found within the specified range. This ensures uniqueness while still using the Random
class.
The above is the detailed content of How to Generate Truly Unique Random Numbers in C#?. For more information, please follow other related articles on the PHP Chinese website!