Home >Backend Development >C++ >How to Generate Truly Unique Random Numbers in C#?

How to Generate Truly Unique Random Numbers in C#?

DDD
DDDOriginal
2025-01-21 13:01:14214browse

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()

The

Random.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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn