用等概率产生0或1的生成器,以不同概率得到1、2、3

一、问题描述:

已知rand1()等概率返回0或1,写一个函数以1/5概率输出1、2/5概率输出2、 2/5概率输出3。

二、代码实现与验证

#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
int rand1(){
    return rand()%2;
}
int rand_test(){
    int a = rand1();
    int b = rand1();
    int c = rand1();
    int res = a + (b << 1) + (c << 2);
    if(res == 0){
        return 1;
    }else if(res == 1 || res == 2){
        return 2;
    }else if(res == 3 || res == 4){
        return 3;
    }else{
        return rand_test();
    }
}
int main()
{
    map<int, int> cnt;
    for(int i = 0; i < N; i++){
        int num = rand_test();
        cnt[num] ++;
    }
    for(auto& p: cnt){
        cout<<p.first<<":"<<p.second*1.0/N<<endl;
    }
    return 0;
}

输出:

1:0.199
2:0.3987
3:0.4023 

posted on 2022-01-20 00:11  七昂的技术之旅  阅读(166)  评论(0)    收藏  举报

导航