Home >Backend Development >C++ >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:
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!