Boost logo

Boost Users :

Subject: [Boost-users] Random library, discrete distribution
From: Kevin Martin (kev82_at_[hidden])
Date: 2009-04-05 13:11:22


I made a post sometime last year about requiring a distribution that
could generate enums with specified probabilities. I find I am
regularly requiring a discrete distribution like this - where I
specify the probabilities. Am I the only one who requires it, or would
it be useful to a wider audience? I'm just wondering whether to submit
a feature request for it or not?

Thanks,
Kevin Martin

This is what I'm using at the moment:

template<class IntType = int>
class discrete_distribution
{
public:
     typedef boost::uniform_int<>::input_type input_type;
     typedef IntType result_type;

     template<size_t N>
      discrete_distribution(const boost::array<int, N> &outputs,
      const boost::array<int, N> &weights) : outputs_(outputs.begin(),
      outputs.end()), weights_(weights.begin(), weights.end()) {
         for(int i=1;i!=weights_.size();++i) weights_[i] +=
weights_[i-1];
     }

     inline void reset() {}

     template<class Engine>
     result_type operator()(Engine& eng) {
         boost::uniform_int<> ui(0, weights_.back()-1);
         boost::variate_generator<Engine&, boost::uniform_int<> >
vg(eng, ui);

         int idx = std::lower_bound(weights_.begin(), weights_.end(),
vg())
          - weights_.begin();
         return outputs_[idx];
     }
private:
     std::vector<int> outputs_;
     std::vector<int> weights_;
};


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net