Generate “In-Range” Random Numbers in C

后端 未结 3 1007
一个人的身影
一个人的身影 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 06:52

    Try out this algorithm for pseudo-random numbers:

    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.
    

    Note that this is subject to a modulo bias, but it should work for what you need.

提交回复
热议问题