Home > Backend Development > C++ > How to Generate Non-Repeating Random Numbers in C#?

How to Generate Non-Repeating Random Numbers in C#?

Linda Hamilton
Release: 2025-01-21 13:11:10
Original
844 people have browsed it

How to Generate Non-Repeating Random Numbers in C#?

Generate unique random numbers in C#

In the development of applications that need to generate random unique numbers, developers often encounter problems with the System.Random class. Even if you use DateTime.Now.Ticks as a seed, there may still be duplicate numbers.

Solve duplicate value problem

System.Random.Next() itself does not guarantee the uniqueness of the generated numbers. When combined with a narrower range (e.g. 0 to 10), the probability of encountering duplicate values ​​is higher.

Alternative: List Maintenance

To overcome this limitation, a more robust approach is to maintain a list of generated numbers. Duplication can be avoided by checking whether the potential number already exists in the list.

The following is a modified implementation using this strategy:

<code class="language-csharp">public Random a = new Random();
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);
}</code>
Copy after login

This approach ensures the creation of truly unique values ​​by maintaining a list of generated numbers and filtering out duplicates.

The above is the detailed content of How to Generate Non-Repeating Random Numbers in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template