0

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?

rbm
  • 3,243
  • 2
  • 17
  • 28
bburak
  • 11
  • 1
  • 3
    Of topic: `int array[3];` -> `int array[4];` – Support Ukraine Mar 14 '17 at 15:18
  • 4
    If you want them to be unique fill an array with the values 0..5 then shuffle it, e.g. fisher-yates http://stackoverflow.com/questions/6127503/shuffle-array-in-c – Alex K. Mar 14 '17 at 15:22
  • 2
    Just because the same number appears twice in a row doesn't mean it's not random. – dbush Mar 14 '17 at 15:23
  • 2
    Why do you think a number should not be repeated. If the number is a (pseudo) random number then you should expect *any* result, including the same as the last. The probability will be increasing when you reduce the number space. – harper Mar 14 '17 at 15:23
  • Format your code correctly. This is important. Really, – Jabberwocky Mar 14 '17 at 16:07

2 Answers2

0

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;
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
-1

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());
}
avysk
  • 1,973
  • 12
  • 18