C#如何快速生成随机且不重复的整数集合

实现思路,用循环生成不重复整数集合list,然后循环随机从list中取出一个整数放入newList中,然后从list中删除该整数,最后返回newList,很简单哈哈哈,见代码

随机生成不重复整数集合

关键部分在于while循环 条件list.Count>0,以及随机索引index取值random.Next(0,list.Count),这样可以确保索引不超出list索引范围。

贴上代码吧

public List Generate(int min, int max){     var list = new List();     for (var i = min; i <= max; i++)     {         list.Add(i);     }     var newList = new List();     var random = new Random();     while (list.Count > 0)     {         var index = random.Next(0, list.Count);         newList.Add(list[index]);         list.RemoveAt(index);     }     return newList;}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章