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

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

 

        //获取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 c#

相关文章
相关标签/搜索