Home c# Generate random numbers without repeating

Generate random numbers without repeating [duplicate]

Author

Date

Category

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:

  1. Repeat 20 times;
  2. A = Random number from range [minimum; maximum – number of steps + step number];
  3. Looking for A in the list of results;
  4. 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.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions