Generate “In-Range” Random Numbers in C

后端 未结 3 964
一个人的身影
一个人的身影 2021-02-10 06:32

I need to generated random numbers in the range [0, 10] such that:

  • All numbers occur once.
  • No repeated results are achieved.

Can someone pl

3条回答
  •  梦如初夏
    2021-02-10 07:12

    The algorithm in Richard J. Ross's answer is incorrect. It generates n^n possible orderings instead of n!. This post on Jeff Atwood's blog illustrates the problem: http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

    Instead, you should use the 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;
    }
    

提交回复
热议问题