generate random numbers with no repeat in c#

25,287

Solution 1

With such a small list of numbers to choose from you can simply generate a list that contains all of them and then shuffle them.

Solution 2

Your problem is that you are creating the Random object in every loop. The Random object must be created only once. Try this instead:

Random rnd = new Random(); // <-- This line goes out of the loop        
for (int i = 0; i < 20; i++) {
    int temp = 0;
    temp = rnd.Next(0, 9);
    page[i] = temp;
}
Share:
25,287
tshepang
Author by

tshepang

I do software development for a living and as a hobby. My favorite language is Rust, and I've used Python much in the past. My OS of choice is Debian.

Updated on January 15, 2020

Comments

  • tshepang
    tshepang over 4 years

    How can I generate random numbers with no repeat in C#. I have one array and I want to fill every room with random numbers from 0 to 9. Each room shoud have diffrent numbers. I use this:

    for (int i = 0; i < 20; i++)
    {
        Random rnd = new Random();
        int temp = 0;
        temp = rnd.Next(0, 9);
        page[i] = temp;
    }
    

    But I get same number in evey room's of array.

    • Security Hound
      Security Hound about 12 years
      "I just want to know how i can generate random numbers with no repeat in c#?" - This is not possible. A random number is suppose to repeat otherwise its not actually a random number generator but a unique value generator which is trival to code. Your code is also flawed because you will always have the same seed value.
    • Werner Henze
      Werner Henze over 8 years
      You talk about rooms but have a page array!? Do you mean every entry in array page shall be unique? Do I understand you right that you want 20 digits in page, all being distinct?
  • Admin
    Admin over 10 years
    Also this is not at all efficient for large array instead you may create a sorted array and use one shuffling techniques to create the randomness
  • Benvorth
    Benvorth over 9 years
    Can you explain your answer a bit more?