原理不必多说,代码很简单,应该可以看得懂,网上早有介绍,在此用c写一个保存以后直接用:
/*在区间【low,high】之间取num个互不相同的随机数(包括low,hight)
思路:先先初始化一个int型的数组,将区间所有值赋予它,然后生成随机下标,
将swapArray[hight-low-i]赋值于swapArray[temp],逐步靠近i_array[0]
*/
int *getRandomNumbers(int low,int hight,int num)
{
//入参判断
if(0 > num)
{
return NULL;
}
//交换
if(low > hight)
{
low = low ^ hight;
hight = low ^ hight;
low = low ^ hight;
}
//合法性判断
if( (hight-low+1) < num)
{
printf("所给区间[%d , %d]太小,不可能取出%d个不同随机数",low,hight,num);
return NULL;
}
int *radnomNumbersArray = NULL;//存放取出的随机数
int swapArray[hight-low+1];
int i = 0;
int count = 0;//记录执行次数
//初始化
radnomNumbersArray = (int *)malloc(num);
memset(radnomNumbersArray, 0, sizeof(int)*num);
memset(swapArray, 0, sizeof(swapArray));
for(i = 0; i < hight-low+1; i++)
{
swapArray[i] = i + low;
}
srand((unsigned)time(NULL)); //设置随机数产生种子
for(i = 0; i < num; i++)
{
int temp = (int)rand()%(hight-low+1-i);
radnomNumbersArray[i] = swapArray[temp];
swapArray[temp] = swapArray[hight-low-i];
count++;
}
for(i = 0; i < num; i++)
{
printf("num = %d\n",radnomNumbersArray[i]);
}
printf("程序运行 %d 次\n",count);
return radnomNumbersArray;
}
Java版:
/**返回的最大值是startValue+count-1
* @param needCount
* @param count
* @param starValue
* @return
*/
public static List randomNoRepeatArray(int needCount,int count,long startValue){
if(needCount>count) return null;//这种情况 会出现无限循环的
Random random = new Random();
int[] swapArray = new int[count];
for(int i=0; i
swapArray[i] = i;
}
List radnomNumbersArray = new ArrayList();
while(radnomNumbersArray.size() < needCount){
int temp = random.nextInt(count);
if(swapArray[temp] != -1){
radnomNumbersArray.add((int) (temp+startValue));
swapArray[temp] = -1;
}
}
swapArray = null;
return radnomNumbersArray;
}