等概率随机函数和任意概率随机函数

来源:互联网 发布:手机照片墙软件 编辑:程序博客网 时间:2024/04/29 19:20

from peking2@mitbbs

题目:Given a function that will return 0 or 1 at the equal probability 0.5, called prob(), write a function biased_fun(double p), will return 1 with probability p.

我的一个面试题目和这个很相似

int equal_prob(){return rand()%2;}int prob(double p, int target){if(p<0.5)return prob(1-p, !target);if(equal_prob() == target)return target;elsereturn prob((p-0.5)*2, target);}


另外这个题目还有一个变种:Given a biased_coin(), write a function that will return 0 or 1 with equal probability 0.5

int biased_coin();int fair_coin(){int first = biased_coin();int second = biased_coin();if(first==0 && second==1)return 1;if(first==1 && second==0)return 0;return fair_coin();}