dimanche 19 mars 2017

How to find n random elements from an array of m elements where n<=m in C?

Suppose I have the array A = {3,4,5,6,7}. How do I select any n random number elements from it such that I get a unique set of numbers?

For example, if I want to select any three random numbers from this array, the output should not have any repeated element. E.g, the output cannot be {3,4,4}.

I tried writing the code :

int count = 0;
int n = 2;
int x;
int sizeofarray = 5;

while(count < n)
{
    srand(time(NULL));
    x = rand()%(sizeofarray);
    printf("%d ", x);
    count++;
}




Aucun commentaire:

Enregistrer un commentaire