题目:假设你希望以各1/2的概率输出0和1。你可以自由使用一个输出0或1的过程brandom.它以概率p输出1,1-p输出0,不知道p直,给一个利用brandom的算法返回0和1的概率为1/2.
解答:
#include<iostream.h>
#include<time.h>
#include<stdlib.h>
#define MinProb 3.05185094759972e-5
bool happened(double probability)//probability 0~1
{
if(probability<0)return false;
if(probability<MinProb)
return rand()==0&&happened(probability/MinProb);
if(rand()<=probability*RAND_MAX)
return true;
return false;
}
bool happened2(double p){
bool m1,m2;
while(1){
m1=happened(p);
m2=happened(p);
if(m1!=m2)
return m1;
}
}
void main()
{
long happen=0;
srand(time(0));
for(long i=0;i<1000000;++i)
if(happened2(0.9))++happen;
cout<<happen<<endl;
}