Home >Backend Development >C++ >How Can I Generate Unique Random Numbers Without Duplicates?
Avoid duplicate random number generators
When generating random numbers for lottery tickets or other scenarios, it is crucial to ensure that the numbers in the same row are unique. The code originally provided did not address this issue and may have resulted in duplication.
Solving duplicate issues
To solve this problem, the generated numbers must be stored in a collection. Each time a new number is selected, check if it already exists in the set. If present, generate a new number until a unique number is found.
Use different methods
Alternatively, a more efficient approach is to generate a sequence of numbers between 1 and 49, randomly shuffle them, and then select the first six numbers from the shuffled sequence. This ensures uniqueness without the need for constant checking.
Here is the improved code using this method:
<code>var rnd = new Random(); var randomNumbers = Enumerable.Range(1, 49).OrderBy(x => rnd.Next()).Take(6).ToList();</code>
This code generates a random sequence, then shuffles it and selects the first six numbers, guaranteed to have no duplicates.
The above is the detailed content of How Can I Generate Unique Random Numbers Without Duplicates?. For more information, please follow other related articles on the PHP Chinese website!