I am trying to create random integer array generator with no duplicate by using this:
int pt_rand(int nbits) {
int mask;
if (0 < nbits && nbits < sizeof(int)*8) {
mask = ~(~((unsigned int) 0) << nbits);
}
else {
mask = ~((unsigned int) 0);
}
return rand() & mask;
}
int *gen_rand_int_array_nodups(int length, int nbits) {
int * a = malloc(sizeof(int)*length);
for (int i = 0; i < length; i++) {
a[i] = pt_rand(nbits);
for (int j = 0; j < i; j++) {
do {
a[i] = pt_rand(nbits);
} while (a[i] == a[j]);
}
}
shuffle_int_array(a, length);
return a;
}
This code is trying to generate unique random integers within given nbits by checking elements one by one. However, I'm still getting duplicates in the result and I've not figured it out why. I know this is a bad practice of using this method to generate unique random numbers but the requirement of my assignment requires me to somehow make use of nbits param. I've looked up for the easiest way to the same thing by filling an array with increment number and swap them around but that's just an alternative solution and I still have to confirm if I'm allowed to use that instead.
Aucun commentaire:
Enregistrer un commentaire