mercredi 18 novembre 2015

Generating unequal random numbers in C

I have written a program that generates 4 random digits, that should appear on the screen like this: from 0000 to 9999 (not in ascending order necessarily, of course!).

The problem is that I have encountered numbers that are equal with each other. How can I fix it? I just want to produce 10.000 numbers, in the range 0000 to 9999, but not in any order: just "random".

Here is what I have written so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define SIZE 10000

int main(){

    srand(time(NULL));

    int a[SIZE], b[SIZE], c[SIZE], d[SIZE], i;
    FILE *fd = fopen("combinations_rand.txt", "w");
    assert(fd);

    for(i=0; i<SIZE; i++){      
        a[i] = rand()%10; //array of first digits
        b[i] = rand()%10; //array of second digits, etc...
        c[i] = rand()%10;
        d[i] = rand()%10;
        fprintf(fd, "%d%d%d%d\n", a[i], b[i], c[i], d[i]);
     }
     fclose(fd);
}




Aucun commentaire:

Enregistrer un commentaire