Aje*_*nga 2 algorithm probability
给定一个功能
int rand1();
Run Code Online (Sandbox Code Playgroud)
以相等的概率返回0或1,实现一个函数
int rand5();
Run Code Online (Sandbox Code Playgroud)
以相等的概率返回0,1,2,3,4,5.
!扭!在将其标记为重复之前阅读...
你可以调用rand1()的次数是固定的.你可以决定它是10或20或100,但不是任何数量的rand1()调用.即rand1()调用的数量有一个上限.此外,您必须保证rand5()应始终以相同的概率将o返回到5.代码偏向于少数额外的0和1是不可接受的.
如果你认为编写这样的函数是不可能的,那么你可以让我们都知道,为什么它不可能.
编辑:这就是我所拥有的,我认为这还不够
int rand5()
{
bitset<3> b;
b[0] = rand1();
b[1] = rand1();
b[2] = rand1();
int i = b;
if(b >= 6)
return rand5();
return i;
}
Run Code Online (Sandbox Code Playgroud)