Friday, November 25, 2016

Random Numbers with Exceptions

[Question]
Write a function to generate random numbers in [0, N-1], excluding numbers in a given list. For example, N=10, the excluding list is {4, 6, 9}, then a random number is valid when it is not 4, or 6, or 9.

[Analysis]
This is another question that Reservior Sampling can be applied. The generator function will exclude the numbers in the range and give the equal possibility to the rest.

When there is only one number is excluded, the solution can be as simple as, generate one number from [0, N-2], if the generated number is equal to the excluded number, return N-1. This is a special case of Reservior Sampling.

[Solution]
int rand_except(int n, unordered_set<int>& exp) {
     int res=-1, count=0;
     for (int i=0; i<n; i++) {
          if (exp.count(i)>=0) continue;
          if ( rand()%(++count)==0 ) res = i;
     }
     return res;
}

No comments:

Post a Comment