Tell me how to generate, for example, 20 random numbers, in the range 1-50, without repeating. Through the Random class, I only know that there are repetitions, can I somehow do without them?

## Answer 1, authority 100%

```
var rand = new Random ();
var knownNumbers = new HashSet & lt; int & gt; ();
var arr = new int [20];
for (int i = 0; i & lt; arr.Length; i ++)
{
int newElement;
do
{
newElement = rand.Next (50);
} while (! knownNumbers.Add (newElement));
arr [i] = newElement;
Console.WriteLine (arr [i]);
}
```

Terribly inefficient, and will loop if the range is less than the length of the array.

## Answer 2, authority 99%

You are all from the same university, right?

Here’s a classic random shuffle.

```
const int n = 20;
int [] perm = Enumerable.Range (0, n) .ToArray (); // 0 1 2 ... (n - 1)
// if this is NOT a tutorial, do not create a new Random here, but start
// one global, otherwise the values will always be the same
Random r = new Random ();
for (int i = n - 1; i & gt; = 1; i--)
{
int j = r.Next (i + 1);
// exchange perm [j] and perm [i]
int temp = perm [j];
perm [j] = perm [i];
perm [i] = temp;
}
```

_{Code borrowed from this answer . }

## Answer 3, authority 100%

I suggest the following algorithm:

- Repeat 20 times;
- A = Random number from range [minimum; maximum – number of steps + step number];
- Looking for A in the list of results;
- If we find a repeat, increase A by one and go to step 3 .;

## Answer 4, authority 100%

I propose another algorithm: make an array of 20 increasing numbers from 1 to 50 (no repetitions), then shuffle them.