生成不重复的随机整数

2009年2月18日星期三

生成不重复的随机整数

论坛上总有人在问如何生成不重复的随机数,写一个我惯用的方法,效率很高的:



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

static List GetRandomArray(int maxNumber,int count)
{
List list = new List();//保存取出的随机数
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;
}
//获取count个不大于maxNumber的整数,所有整数不重复。当然,count必须小于等于maxNumber

static List GetRandomArray(int maxNumber,int count)
{
List list = new List();//保存取出的随机数
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;
}

    0 评论:

    发表评论