在你引用的答案中,算法的C实现示例如下:
#define M 10
#define N 100
int in, im;
im = 0;
for (in = 0; in < N && im < M; ++in) {
int rn = N - in;
int rm = M - im;
if (rand() % rn < rm)
/* Take it */
vektor[im++] = in + 1; /* +1 since your range begins from 1 */
}
The Knuth algorithm. This is a very simple algorithm with a complexity of O(N) (i.e. the numeric range), meaning that it is most usable when M is close to N.
但是你设置M == N,它不是接近但是相等
所以rn和rm的初始值是相同的.所以这不能使算法正常工作,因为:
whatever % rn < rm
总是如此,如345436%22
I basically need to shuffle the array of numbers from 0 to n
这个算法并不是你所需要的:它根本不会对数组进行混洗,它会通过从不断增加的值中选择一个来产生有序的随机数(因此,唯一).像你一样限制值会强制算法发出范围的所有值.