首页 > Web开发 > 详细

.net中如何生成不重复的随机数

时间:2015-09-14 12:32:02      阅读:276      评论:0      收藏:0      [点我收藏+]

.net中生成不重复的随机数的方法

 

        //获取count个不大于maxNumber的整数,所有整数不重复。当然,count必须小于等于maxNumber

        static List<int> GetRandomArray(int maxNumber,int count)
        {
            List<int> list = new List<int>();//保存取出的随机数
            int[] array=new int[maxNumber];//定义初始数组
            for (int i = 0; i < maxNumber; i++)//给数组元素赋值
                array[i] = i + 1;
            Random rnd = new Random();
            for (int j = 0; j < count; j++)
            {
                int index = rnd.Next(j,maxNumber);//生成一个随机数,作为数组下标
                int temp = array[index];//从数组中取出index为下标的数
                list.Add(temp);//将取出的数添加到list中
                array[index] = array[j];//将下标为j的数交换到index位置
                array[j] = temp;//将取出的数交换到j的位置
            }
            return list;
        }



参考资料:.net中生成不重复的随机数   http://www.studyofnet.com/news/977.html


.net中如何生成不重复的随机数

原文:http://my.oschina.net/u/2428791/blog/505742

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!