如何以指定的概率运行部分代码?

时间:2016-01-22 05:24:01

标签: c++ c++11 random

我有一个变量$(document).ready(function(){ $('#singlepage').pageMe({ pagerSelector:'#Para1', childSelector:'.panel', perPage: 4, showPrevNext: false, numbersPerPage: 5, hidePageNumbers: false, showFirstLast: true }); $('#singlepage2').pageMesupp({ pagerSelector:'#Para2', childSelector:'.panel', perPage: 4, showPrevNext: false, numbersPerPage: 5, hidePageNumbers: false, showFirstLast: true }); $('#singlepage3').pageMecarr({ pagerSelector:'#Para3', childSelector:'.panel', perPage: 4, showPrevNext: false, numbersPerPage: 5, hidePageNumbers: false, showFirstLast: true }); }); ,其值通过cnt语句检查如下:
如果if/else,请致电cnt<=2
如果func,则以cnt > 2的概率调用func 如何在C ++中实现基于概率的代码执行?

P=3/(2*cnt)

2 个答案:

答案 0 :(得分:6)

使用类似std::uniform_real的内容:

#include <random>

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);

void func() {
    // Probability 0.3
    if(dis(gen) < 0.3)
        sendMsg();
}

答案 1 :(得分:1)

std::map::lower_bound + partial_sum + C ++ 11 lambdas

这是一个概括,您可以轻松地给出每个lambda的概率。

#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <random>
#include <vector>

int main() {
    typedef std::pair<double, std::function<void()>> P;
    auto v = std::vector<P> {
        {0.2, [](){std::cout << "a" << std::endl;}},
        {0.5, [](){std::cout << "b" << std::endl;}},
        {0.3, [](){std::cout << "c" << std::endl;}}
    };
    std::partial_sum(v.begin(), v.end(), v.begin(),
        [](const P& x, const P& y){return P(x.first + y.first, y.second);}
    );
    auto m = std::map<P::first_type, P::second_type>(v.begin(), v.end());
    std::random_device r;
    std::mt19937 prng(r());
    std::uniform_real_distribution<> dist(0.0, 1.0);
    for (auto i = 0u; i < 10u; ++i) {
        auto r = dist(prng);
        std::cout << r << std::endl;
        m.lower_bound(r)->second();
        std::cout << std::endl;
    }
}

示例输出:

0.255392
b

0.0884198
a

0.8279
c

0.095513
a

0.34819
b

0.20279
b

0.327021
b

0.402535
b

0.64069
b

0.848767
c

相关:How do I select a range of values in a switch statement?