dimanche 4 novembre 2018

Generating different random arrays in C [duplicate]

This question already has an answer here:

I use srand(time(NULL)) in my main function but i cant generate two random arrays.

I wrote a function which will generate a random array with different numbers in it.My goal is generate numbers between 1 and size of the array.But when i call this function twice,i get exactly same arrays.

void randomArray(int *array,int size){
    int i=0;
    int j=0;
    int randNumber;
    int test;
    while(i<size){
        test=0;
        while(test==0){
            test=1;
            j=0;
            randNumber=(rand()%(size))+1;
            while (j<i){
                if(array[j]==randNumber){
                    test=0;
                }
                j++;
            }
        }
        array[i]=randNumber;
        i++;
    }
}

Example output;

Array1: 13 18 2 4 15 9 14 7 16 17 20 19 6 10 1 8 3 5 12 11

Array2: 13 18 2 4 15 9 14 7 16 17 20 19 6 10 1 8 3 5 12 11

I researched about this a bit and i learned its because srand(time(NULL)) generates random numbers using time so i'm getting same arrays because of that.I figured that i could put delay between them but thats not a good solution because i need to put like half second delay for different results.Any other ways to do it?




Aucun commentaire:

Enregistrer un commentaire