Random number array without duplicates in C -


i trying create random integer array generator no duplicate 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 * = malloc(sizeof(int)*length);     (int = 0; < length; i++) {         a[i] = pt_rand(nbits);         (int j = 0; j < i; j++) {             {                 a[i] = pt_rand(nbits);             } while (a[i] == a[j]);         }     }     shuffle_int_array(a, length);     return a; } 

this code trying generate unique random integers within given nbits checking elements 1 one. however, i'm still getting duplicates in result , i've not figured out why. know bad practice of using method generate unique random numbers requirement of assignment requires me somehow make use of nbits param. i've looked easiest way same thing filling array increment number , swap them around that's alternative solution , still have confirm if i'm allowed use instead.

    (int j = 0; j < i; j++) {         {             a[i] = pt_rand(nbits);         } while (a[i] == a[j]);     } 

say i=3, j=1, a={5,2,3,2}. detect have 2 ... pt_rand() gives 5 now. how detect have 5?

corrected version:

int *gen_rand_int_array_nodups(int length, int nbits) {     int * = malloc(sizeof(int)*length);     (int = 0; < length; i++) {         int duplicate;                 {             duplicate = 0;             a[i] = pt_rand(nbits);             (int j = 0; j < i; j++) {                 if (a[j] == a[i])                 {                     duplicate = 1;                     break;                 }             }         } while (duplicate);     }     shuffle_int_array(a, length);     return a; } 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -