C Programming – Generate Array of Random Numbers in a Given Range

c++

i want to generate an array of random numbers for example if the range is [0,10] then the desired output to be
2 3 5 6 4 7 8 9 0 1 ( non repeatitive )

the problem i am facing with rand() function is sometimes i get some repeated nos , i was discrete values in that range , and different order everytime i invoke.

Ps: I did go through some of the threads
Generate a random double in a range
Generate random numbers uniformly over an entire range
in here and couldnt fine one similar mine, there is a subtle difference. expecially the latter one is pretty close

Best Answer

It seems more a problem of shuffling that of randomization.

A good start is the Fisher-Yates shuffle which starts with the sorted array of elements and generate a random permutation:

int size = 10;
int *elements = malloc(sizeof(int)*size);

// inizialize
for (int i = 0; i < size; ++i)
  elements[i] = i;

for (int i = size - 1; i > 0; --i) {
  // generate random index
  int w = rand()%i;
  // swap items
  int t = elements[i];
  elements[i] = elements[w];
  elements[w] = t;
}
Related Question