C/C++随机生成[0,N-1]的序列
用C/C++实现MATLAB中的randperm函数
1、MATLAB中的randperm函数如下:
>> randperm(20)
ans =
13 9 2 17 11 5 3 19 18 10 1 7 14 20 15 6 16 4 12 8
2、C/C++实现randpermC函数如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
void randpermC(int N)
{
int *arr = (int*)malloc(N*sizeof(int));
int count = 0;
memset(arr,0,N*sizeof(int));
srand(time(NULL));
while(count<N)
{
int val = rand()%N;
if (!arr[val])
{
printf("%d ",val);
arr[val]=1;
++count;
}
}
free(arr);
arr = NULL;
}
int main(int argc, char **argv)
{
randpermC(20);
return 0;
}