Posted on 2008-10-14 17:17
kainster 阅读(114)
评论(0) 编辑 收藏
先写个小程序,生成随机数文件,以及读出来统计出现频率
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
//生成随机数文件
FILE *Data;
Data = fopen("dead.txt","w");
if( Data == NULL )
printf( "The file was not opened\n" );
else
{
for( int i=0; i<1000000; i++ )
{
fprintf(Data,"%d,",rand());
}
}
fclose(Data);
//统计出现频率
FILE *inFile;
FILE *outFile;
inFile = fopen("dead.txt","r");
outFile = fopen("dead2.txt","w+");
const int ArrayLength = 1000000;
int* boolArray = new int[ArrayLength];
for(int m = 0; m< ArrayLength; m++)
boolArray[m] = 0;
if(outFile && inFile)
{
while(!feof(inFile))
{
int d = 0;
fscanf(inFile,"%d,",&d);
boolArray[d]++;
}
for(int i=0; i<ArrayLength; i++)
{
fprintf( outFile, "%d : %d,", i,boolArray[i]);
}
}
fclose(outFile);
fclose(inFile);
return 0;
}
然后生成k个在1~n范围内均匀分布的随机数,并且这些数是唯一的
// 产生k个在1~n范围内均匀分布的随机数,并且这些数是唯一的
void GenerateRandomNumbers(int k, int n)
{
int rand1, temp;
int* array = new int[n];
for( int i=0; i<n; i++)
{
array[i] = i+1;
}
for( i=0; i<k; i++ )
{
rand1 = rand() % n;
//swap
temp = array[rand1];
array[rand1] = array[i];
array[i] = temp;
}
for( i=0; i<k; i++ )
{
printf("%d,",array[i]);
}
}