Generate random "inside range" numbers in C

I need to create random numbers in the range [0, 10] so that:

  • All numbers occur once.
  • No repeat results have been achieved.

Can someone please call me which algorithm to use?

+5
source share
3 answers

Richard J. Ross's response algorithm is incorrect. It generates n^npossible orders instead n!. This Jeff Atwood blog post illustrates the issue: http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

Instead, you should use Shuffle Knuth-Fisher-Yates:

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;
}
+11
source

Try 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.

, , , .

+1

Try creating a randomization function, for example:

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<i; j++) {
                if(v[j] == v[i]) {
                    flag=1;
                    break;
                }
                flag=0;
            }
        } while(flag == 1);
    }
}

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

randomize(v, 11, 11);

The array, because it is passed as an argument by reference, will be randomized, without repeats and with numbers that appear once.

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

0
source