c 生成随机不重复的整数序列

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>

void genNumber(const char *fileName,const int numCount)
{
    int i = 0, j = 0;
    int *arr = (int*)malloc(sizeof(int) * numCount);
    for(;i < numCount; ++i)
    {
        arr[i] = i;
    }
    FILE *fp = fopen(fileName,"w");
    if(NULL == fp){printf("open %s failed\n",fileName);}
    i = numCount;
    while(i != 0)
    {
        j = rand()%i;
        fprintf(fp,"%d ",arr[j]);
        arr[j] = arr[--i];
    }
    fclose(fp);
}

int main()
{
    time_t t = clock();
    genNumber("num.txt",10000000);
    printf("use time:%lu ms\n",clock() - t);
    return 0;
}

 

以下代码用于检测生成的数列,是否正确:

#include <stdio.h>
#include <malloc.h>
#include <memory.h>
#include <time.h>

void checkNum(const char* fileName)
{
    int size = 0,numCount = 0,i = 0,j = 0,max = 0;
    char *buf = NULL;
    printf("checking %s ...\n",fileName);
    FILE *fp = fopen(fileName,"r");
    if(NULL == fp){printf("open %s error!\n",fileName);}
    fseek (fp , 0 , SEEK_END);
      size = ftell (fp);
      rewind(fp);
      buf = (char*)malloc(sizeof(char)*size);
      fread(buf,1,size,fp);
      for(i = 0;buf[i];++i)
      {
          if(buf[i] == ' '){++numCount;}
      }
      free(buf);
      rewind(fp);
      buf = (char*)malloc(sizeof(char)*numCount);
      memset(buf,0,sizeof(char)*numCount);
      for(i=0;i<numCount;++i)
      {
          fscanf(fp,"%d ",&j);
          if(buf[j] != 0)
          {
              printf("[ %d ] show %d times\n",j,(int)buf[j] + 1);
          }
          ++buf[j];
          if(j > max){max = j;}
      }
      fclose(fp);
      free(buf);
      printf("size = %d, numCount = %d, max = %d\n",size,numCount,max);
}

int main(int argc,char *argv[])
{
    if(argc != 2)
    {
        printf("argv error!\n");
        return 0;
    }
    time_t t = clock();
    checkNum(argv[1]);
    printf("use time:%lu ms\n",clock() - t);
    return 0;
}

 

posted @ 2016-08-15 14:55  你好阿汤哥  Views(972)  Comments(0Edit  收藏  举报