mercredi 28 juin 2017

Random generation algorithm in C++

Suppose you need to generate a random permutation of the first N integers. For example, {4, 3, 1, 5, 2} and {3, 1, 4, 2, 5} are legal permutations, but {5, 4, 1, 2, 1} is not, because one number (1) is duplicated and another (3) is missing. This routine is often used in simulation of algorithms. We assume the existence of a random number generator, RandInt(i,j), that generates between i and j with equal probability. Here are is the algorithm:

Fill the array A from A[0] to A[N-1] as follows: To fill A[i], generate random numbers until you get one that is not already in A[0], A[1],…, A[i-1].

Implement this algorithm in C++ and find the complexity. This is my code:

int a;
bool b = false;
A[0] = RandInt(1,n);
for (int i=1;i<n;i++) {
do {
  b = false;
  a = RandInt(1,n);
  for (int j=0;j<i;j++)
     if(A[j] == a)
        b = true;
} while(b);
A[i] = a;
}

Is this code correct? And how can I find the complexity of the algorithm? Since, RandInt(i,j) generates random numbers, I don't know how many times the do while loop will be repeated.




Aucun commentaire:

Enregistrer un commentaire