filling a array with uniqe random numbers between 0-9 in c#

后端 未结 4 1051
一整个雨季
一整个雨季 2020-12-07 05:58

I want to fill my array with unique random numbers between 0-9 in c# I try this function:

    IEnumerable UniqueRandom(int minInclusive, int maxIn         


        
相关标签:
4条回答
  • 2020-12-07 06:33

    You're much better off doing something like this, using a Fischer-Yates shuffle:

    public static void Shuffle<T>(this Random rng, IList<T> list)  
    {  
        int n = list.Count;  
        while (n > 1) {  
            n--;  
            int k = rng.Next(n + 1);  
            T value = list[k];  
            list[k] = list[n];  
            list[n] = value;  
        }  
    }
    

    Usage:

    var numbers = Enumerable.Range(0, 10).ToList(); // 0-9 inclusive
    var rng = new Random();
    rng.Shuffle(numbers);
    int[] page = numbers.Take(3).ToArray();
    
    0 讨论(0)
  • 2020-12-07 06:34

    Your method returns an enumerable, but you try to assign a single value. Assign all the values in one step:

    int[] page = UniqueRandom(0, 9).Take(3).ToArray();  // instead of your loop
    

    EDIT: From your comments, I judge that you might have copied the code you have shown us without understanding it. Maybe you want to fill your array with random numbers with repetitions possible (e.g. 1, 6, 3, 1, 8, ...)? Your current code only uses each value once (hence the name unique), so you cannot fill an array of size larger than 10 with it.

    If you just want simple random numbers, there's no need for this method at all.

    var rnd = new Random();
    
    // creates an array of 100 random numbers from 0 to 9
    int[] numbers = (from i in Enumerable.Range(0, 100) 
                     select rnd.Next(0, 9)).ToArray();
    
    0 讨论(0)
  • 2020-12-07 06:37

    my array is too big, i need many random numbers...and when i used

     int[] page = UniqueRandom(0, 9).Take(arraysize).ToArray(); 
    

    it gave me exactly 9 unique random numbers..

    and i got this error(for example for arraysize = 15) :

    index was outside of bounds of array
    

    how i can have a array with too many random numbers between 0-9 without repeat?

    0 讨论(0)
  • 2020-12-07 06:45

    You could do this:

    int i = 0;
    foreach (int random in UniqueRandom(0, 9).Take(3))
    {
        page[i++] = random;
    }
    
    0 讨论(0)
提交回复
热议问题