LocARNA-1.9.2
src/LocARNA/discrete_distribution.hh
00001 #ifndef LOCARNA_DISCRETE_DISTRIBUTION
00002 #define LOCARNA_DISCRETE_DISTRIBUTION
00003 
00004 #ifdef HAVE_CONFIG_H
00005 #include <config.h>
00006 #endif
00007 
00008 namespace LocARNA {
00009 
00010     // ------------------------------------------------------------
00013     class DiscreteDistribution {
00014     private:
00015         std::vector<double> distrib_acc_;
00016 
00017     public:
00023         explicit
00024         DiscreteDistribution(const std::vector<double> &distvec) {
00025             if (distvec.size() == 0)
00026                 return;
00027 
00028             distrib_acc_.resize(distvec.size());
00029 
00030             distrib_acc_[0] = distvec[0];
00031             for (size_t i = 1; i < distvec.size(); i++) {
00032                 distrib_acc_[i] += distrib_acc_[i - 1] + distvec[i];
00033             }
00034             double max_acc = distrib_acc_[distvec.size() - 1];
00035             for (size_t i = 0; i < distvec.size(); i++) {
00036                 distrib_acc_[i] /= max_acc;
00037             }
00038         }
00039 
00046         size_t
00047         operator()(size_t x) {
00048             double y = x / (double)RAND_MAX;
00049 
00050             size_t i = 0;
00051             for (; i < distrib_acc_.size() && y > distrib_acc_[i]; ++i)
00052                 ;
00053 
00054             assert(i <= distrib_acc_.size());
00055             return i;
00056         }
00057     };
00058 
00059 } // end namespace LocARNA
00060 
00061 #endif // LOCARNA_DISCRETE_DISTRIBUTION
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends