wz生成不重复的随机数的高效的算法
//高效产生随机数
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define SIZE 5
void generateRandom();
int main(){
srand((unsigned)time(NULL));
generateRandom();
return 0;
}
/*
* 产生 1~SIZE 之间的不重复的随机数
* */
void generateRandom(){
int auxiliaryArray[SIZE + 1];
int i;
for( i = 1; i <= SIZE; i++ )
{
auxiliaryArray[i] = i;
}
int random[SIZE + 1];
int length = SIZE;
int temp_random;
for( i = 1; i <= SIZE; i++ )
{
temp_random = rand()%length + 1;
printf("1.temp_random=%d, length=%d, auxiliaryArray[temp_random]=%d ;\n", temp_random, length, auxiliaryArray[temp_random]);
random[i] = auxiliaryArray[temp_random];
auxiliaryArray[temp_random] = auxiliaryArray[length--];
printf("2.temp_random=%d,i=%d,random[i]=%d, auxi[temp_random]=%d,length=%d\n\n", temp_random,i,random[i],auxiliaryArray[temp_random],length);
}
printf("random sequence without repeated:\n");
for( i = 1; i <= SIZE; i++ )
{
printf("%-3d ", random[i]);
if(i%10 == 0)
printf("\n");
}
}
测试截图:
本文转载自CSDN博主「土肥宅娘口三三」的原创文章
原文链接:.
https://blog.csdn.net/robin_Xu_shuai/article/details/51454347