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

How to Generate Six Unique Random Numbers in C#?

DDD
DDDOriginal
2025-01-12 13:37:46892browse

How to Generate Six Unique Random Numbers in C#?

Avoid duplication: C# random number generator

Your code is designed to generate six random numbers between 1 and 49. However, these numbers may contain duplicates, which is unacceptable in a lottery-like scenario. To solve this problem, we will explore an efficient way to generate unique random numbers in C#.

Solution:

Store the generated numbers in a collection. Each time a new number is generated, check whether it already exists in the set. If it exists, continue generating another number until you find a unique number.

Here is a modified version of your code that implements this solution:

<code class="language-csharp">var randomNumbers = new List<int>();
var random = new Random();

while (randomNumbers.Count < 6)
{
    int randomNumber = random.Next(1, 50); // 生成1到49之间的随机数
    if (!randomNumbers.Contains(randomNumber))
    {
        randomNumbers.Add(randomNumber);
    }
}</code>

Alternatively, we can adopt the following strategy:

Shuffle the deck and choose method:

  1. Create a sequence of numbers from 1 to 49.
  2. Shuffle the sequence using a random function.
  3. Select the first six numbers from the shuffled sequence.

Here is the code for this approach:

<code class="language-csharp">var rnd = new Random();
var randomNumbers = Enumerable.Range(1, 49).OrderBy(x => rnd.Next()).Take(6).ToList();</code>

This approach guarantees the generation of unique random numbers without the need for custom loops or additional checks for duplicates.

The above is the detailed content of How to Generate Six 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