How to get a list of random numbers that should be unique [closed]

坚强是说给别人听的谎言 提交于 2019-12-13 09:15:00

问题


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


来源:https://stackoverflow.com/questions/18568050/how-to-get-a-list-of-random-numbers-that-should-be-unique

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!