Fast weighted random selection from very large set of values

后端 未结 3 669
梦毁少年i
梦毁少年i 2020-12-25 08:32

I\'m currently working on a problem that requires the random selection of an element from a set. Each of the elements has a weight(selection probability) associated with it.

3条回答
  •  长情又很酷
    2020-12-25 09:14

    Assuming that the element weights are fixed, you can work with precomputed sums. This is like working with the cumulative probability function directly, rather than the density function.

    The lookup can then be implemented as a binary search, and hence be log(N) in the number of elements.

    A binary search obviously requires random_access to the container of the weights.

    Alternatively, use a std::map<> and the upper_bound() method.

    #include 
    #include 
    #include 
    
    int main ()
    {
      std::map cumulative;
      typedef std::map::iterator It;
    
      cumulative[.20]='a';
      cumulative[.30]='b';
      cumulative[.40]='c';
      cumulative[.80]='d';
      cumulative[1.00]='e';
    
      const int numTests = 10;
      for(int i = 0;
          i != numTests;
          ++i)
      {
          double linear = rand()*1.0/RAND_MAX;  
          std::cout << linear << "\t" << cumulative.upper_bound(linear)->second << std::endl;
      }
    
      return 0;
    }
    

提交回复
热议问题