Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Random in generating 50 random numbers in c#

Tags:

c#

random

I want to take 50 numbers at random so that there must be no repetition in them using random method.

Below is my code so far:

private void settext()
{      
     int i;
     Queue <int> qe= new Queue<int>(50);
     Random rm= new Random();
     for (int g = 0; g < 50; g++)
     {
         i = rm.Next(1, 50);
         if (!qe.Contains(i))
         {
              qe.Enqueue(i);
         }                
     }
 }
like image 597
PriLee Avatar asked Jan 14 '23 16:01

PriLee


1 Answers

Rather than looping until you find a number which you haven't used yet, I'd suggest just creating a list (or array) with the 50 possible numbers in, and shuffling it. You can then take however many of them you want.

There are plenty of shuffling questions on Stack Overflow, such as this one.

The advantage of this is that the performance is entirely predictable and linear - whereas if you take all 50 numbers out of 50, at the end you'll have to keep generating random numbers until you happen to get the last one. Not so bad for 50, but imagine if you have hundreds of thousands of numbers...

(Also note that your existing code doesn't use the number 20 anywhere, which should ring alarm bells if you're trying to generate just 20 numbers...)

like image 136
Jon Skeet Avatar answered Jan 30 '23 10:01

Jon Skeet