Generate “In-Range” Random Numbers in C

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

    Try to create a randomize function, like this:

    void randomize(int v[], int size, int r_max) {
        int i,j,flag;
    
        v[0] = 0 + rand() % r_max; // start + rand() % end
        /* the following cycle manages, discarding it,
    the case in which a number who has previously been extracted, is re-extracted. */
        for(i = 1; i < size; i++) {
            do {
                v[i]= 0 + rand() % r_max;
                for(j=0; j

    Then, simply call it passing an array v[] of 11 elements, its size, and the upper range:

    randomize(v, 11, 11);
    

    The array, due to the fact that it is passed as argument by reference, will be randomized, with no repeats and with numbers occur once.

    Remember to call srand(time(0)); before calling the randomize, and to initialize int v[11]={0,1,2,3,4,5,6,7,8,9,10};

提交回复
热议问题