Random numbers that do not match each other

2019-09-14 16:12发布

问题:

I want to produce different numbers with C. We can generate a random number using the stdlib library and the srand function.

For example; I want to produce a random number between 0 and 5.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(void)
{
int i;
int n = 4;
int array[3];

srand(time(NULL));

for(i = 0; i < n; i++)
{
   array[i] = rand() % 5; 
   printf("%d\n", array[i]);
}
return 0;

But the same numbers may coincide here.Like this:

2
4
4
1

How can I prevent this?

回答1:

Maybe you can use something like this:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(void)
{
    int i;
    int n = 4;
    int array[4];

    // Fill an array with possible values
    int values[5] = {0, 1, 2, 3, 4};

    srand(time(NULL));

    for(i = 0; i < n; i++)
    {
       int t1 = rand() % (5-i);   // Generate next index while making the
                                  // possible value one lesser for each
                                  // loop

       array[i] = values[t1];     // Assign value
       printf("%d\n", array[i]);

       values[t1] = values[4-i];  // Get rid of the used value by
                                  // replacing it with an unused value
    }
    return 0;
}


回答2:

Instead of random number you can generate random non-zero shift from the previous number:

#include <stdio.h>
#include <stdlib.h>

int myrand() {
        static int prev = -1;
        if (prev < 0)
               prev = rand() % 5;
        prev = (prev + 1 + rand() % 4) % 5;
        return prev;
}

int main(void) {
        int i;
        for (i = 0; i < 20; i++)
                printf("%d\n", myrand());
}