在上一节中,笔者首先想用C实现这个功能,然后进行了探索和挣扎,最后放弃了,网上搜了搜,参考下面的博文
http://blog.csdn.net/woaixfj/article/details/44730783
给了我很大的启发,换种方式思考真的是挺有启发的,这篇博文里边也有两种实现方法,其中的代码也有一些小问题,进行了调整,如下所示
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
int seven_num(int bitnum);
unsigned int *vector_sequence(int num);
unsigned int *vector_random(int num,int bitnum,FILE * file);
void main()
{
time_t start ,end ;
double cost;
int i,j;
int num=9000000;
int bitnum=7;
FILE *txtname=fopen("data.txt","w");
unsigned int *rand_vector=(unsigned int *)malloc(num*sizeof(unsigned int));
//unsigned int *sequence_vector=(unsigned int *)malloc(num*sizeof(unsigned int));
memset(rand_vector,0,num);
//memset(sequence_vector,0,num);
time(&start);
rand_vector=vector_random(num,bitnum,txtname);
//sequence_vector=vector_sequence(num);
time(&end);
cost=difftime(end,start);
printf("%f\n",cost);
system("pause");
}
int seven_num(int bitnum)
{
int number,count;
for (count=0;count<bitnum;count++)
{
if (count==0)
{
number=rand()%10;
while(number==0)
{
number=rand()%10;
}
}
else
{
number=number*10+(rand()%10);
}
}
return number;
}
unsigned int *vector_sequence(int num)
{
int index_max,i,j,end;
unsigned int *sequence_vector = (unsigned int *)malloc(num*sizeof(unsigned int));
unsigned int *result_vector = (unsigned int *)malloc(num*sizeof(unsigned int));
FILE *txtname=fopen("sequence_vector.txt","w");
memset(sequence_vector,0,num);
memset(result_vector,0,num);
srand((unsigned)time(NULL));
index_max=9999999-1000000+1;
for (i=0;i<index_max;i++)
{
sequence_vector[i]=1000000+i;
// printf("[%d] = %d\n",i,sequence_vector[i]);
}
end=index_max-1;
for (j=0;j<index_max;j++)
{
int temp_index=rand()%(end+1);
int temp_value=sequence_vector[temp_index];
sequence_vector[temp_index]=sequence_vector[end];
fprintf(txtname,"%d\n",temp_value);
result_vector[j]=temp_value;
end--;
}
return result_vector;
}
unsigned int *vector_random(int num,int bitnum,FILE * file)
{
int i;
int iter_num=num-1;
unsigned int *flag_vector=(unsigned int *)malloc((num+1000000)*sizeof(unsigned int));
unsigned int *rand_vector=(unsigned int *)malloc(num*sizeof(unsigned int));
memset(flag_vector,0,num+1000000);
memset(rand_vector,0,num);
srand((unsigned)time(NULL));
for (i=0;i<iter_num;i++)
{
int temp;
temp = seven_num(bitnum);
while (flag_vector[temp]==1) //care for : the up bound
temp = seven_num(bitnum);
fprintf(file,"%d\n",temp);
flag_vector[temp]=1;
rand_vector[i]=temp;
}
return rand_vector;
}
1.vector_sequence方法是直接产生顺序序列,这个很简单,然后就是产生一个随机index,将该index上的值放入文件中,然后将最后的数放入该空缺中,然后缩小数组,是一种不错的方法,但是由于index分布很局限,所以生成的随机数真的不是那么随机。
2. vector_random是直接生成的,所以会很随机,大体上的思路还是“位图法”,但是比较浪费空间,其中涉及到了笔者上一节遇到的蛋疼问题,解决方法是seven_number函数,这好像是c语言入门第一课的内容吧,思想被禁锢到根本没想到这么做,哎,汗颜
总结:这两种方法效率好像是vector_squence乱比较快,不过差距不很大,都比上节的C#实现快多了。