在C中生成"范围内"随机数

5 c

我需要生成[0,10]范围内的随机数,这样:

  • 所有数字都出现一次.
  • 没有重复的结果.

有人可以指导我使用哪种算法?

jap*_*iss 11

Richard J. Ross的答案中的算法是错误的.它产生n^n可能的排序而不是n!.Jeff Atwood的博客上的这篇文章说明了这个问题:http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

相反,你应该使用Knuth-Fisher-Yates Shuffle:

int values[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
srand(time(NULL));

for (int i = 10; i > 0; i--)
{
    int n = rand() % (i + 1);

    int temp = values[n];
    values[n] = values[i];
    values[i] = temp;
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*III 1

尝试一下这个伪随机数算法:

int values[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
srand(time(NULL));

for (int i = 0; i < 11; i++)
{
    int swap1idx = rand() % 11;
    int swap2idx = rand() % 11;

    int tmp = values[swap1idx];
    values[swap1idx] = values[swap2idx];
    values[swap2idx] = tmp;
}

// now you can iterate through the shuffled values array.
Run Code Online (Sandbox Code Playgroud)

请注意,这会受到模偏差的影响,但它应该可以满足您的需要。