How to get a list of random numbers that should be

2019-09-24 14:08发布

问题:

In C#, I want to have the list of 5 random numbers, that should contain unique values from 1 to 5? How can I achieve that?

for example: 1,3,2,5,4 or 2,5,1,3,4

i.e. The list must contains 5 random numbers that should be having the numbers from 1 to 5

回答1:

Random rnd = new Random();
var list = Enumerable.Range(1, 5).OrderBy(x => rnd.Next()).ToList();


回答2:

What you need is called shuffling. The Fisher–Yates shuffle I linked let you do that in linear time, that is about the best you can get.

To do that in C#, you can even implement an extension method, that will look like :

    public static Random rand = new Random();
    public static List<T> Shuffle<T>(this List<T> original)
    {
        List<T> lst = new List<T>(original);
        for (int i = lst.Count - 1; i >= 0; i--)
        {
            int j = rand.Next(0, i + 1);
            T tmp = lst[j];
            lst[j] = lst[i];
            lst[i] = tmp;
        }
        return lst;
    }

and then call it with:

var shuffled = lst.Shuffle();


标签: c# random unique