C++中生成[0, N-1]随机序列

输入 随机序列长度,返回 随机序列

int * randpermC(int N)
{
    int *arr = (int*)malloc(N * sizeof(int));
    int *arr2 = (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])
        {
            arr[val] = 1;
            arr2[count] = val;
            ++count;
        }
    }
    return arr2;
}

arr用于标记是否使用,arr2用于记录返回的随机序列

猜你喜欢

转载自www.cnblogs.com/sbj123456789/p/13193710.html