算法导论(Introduction to Algorithms)exercises 5.1-3代码实现Unblased_random
int blased_random() {//返回1的概率为0.1,返回0的概率为0.9;
return rand() % 10 > 8 ? 1 : 0;
}
int unblased_random() {//等概率返回1,0;
int a = 0, b = 0;
for (;a == b;a = blased_random(), b = blased_random());
return a;
}
void test_of_unblased_random() {//测试unblased_random;
int num_1 = 0;
int num_0 = 0;
for (int i = 0;i < 1000000;i++)
unblased_random() == 1 ? num_1++ : num_0++;
cout << "num_0:" << ends << num_0 << endl;
cout << "num_1:" << ends << num_1 << endl;
}
思路:两次调用blased_random();产生序列0,1;1,0概率相同即\((p\cdot (1-p),(1-p)\cdot p)\);返回序列首位即可;