Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

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

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

    IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
    {
        List<int> candidates = new List<int>();
        for (int i = minInclusive; i <= maxInclusive; i++)
        {
            candidates.Add(i);
        }
        Random rnd = new Random();
        while (candidates.Count > 1)
        {
            int index = rnd.Next(candidates.Count);
            yield return candidates[index];
            candidates.RemoveAt(index);
        }
    }

And I use it like this:

for (int i = 0; i < 3; i++)
{
    page[i] = UniqueRandom(0, 9);
}

But I got error :

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'

I also added this name space:

using System.Collections.Generic;

I just don't know how I can convert the function output to int... please help me... thank you...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...