dimanche 17 janvier 2016

How to randomly pick more than one different array elements in C?

first of all I am new to programming and I'm trying to solve this problem. After dynamically creating an array of N integers (N is inserted by the user and the elements are random numbers), I am trying to randomly pick half of the elements (N/2) and randomly modify them. My code for randomly picking and modifying is as follows (b is the array and it's earlier declared in my code):

for(int j=0; j<(N/2); j++){
    int l=rand() % (N + 1 - 0) + 0;
    b[l]= rand() % (100 + 1 - (-100)) + (-100);
}

The problem is that in this way, there is a possibility that the same element is chosen for modification. How can I avoid this? I tried the following code but didn't work out.

int n=-1;
for(int j=0; j<(N/2); j++){
    int l=rand() % (N + 1 - 0) + 0;
    b[l]= rand() % (100 + 1 - (-100)) + (-100);
    if(l == n){
        j--;
    }
    n=l;
}

Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire