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);
}
}
}
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With