编写一个C ++程序来生成0随机分配到5给出RAND1()返回0或1的随机分配、程序

2023-09-11 03:24:38 作者:天会亮心会暖

给出一个函数

  INT RAND1();
 

其中返回0或1,以相同的概率, 实现功能

  INT rand5();
 

返回0,1,2,3,4,5概率相同。

!捻 !!!标记为重复之前,请阅读......

的次数,你可以调用RAND1()是固定的。您可能会决定它是10或20或100的这个问题,但任何数量RAND1()调用。 即有关于RAND1的数量上限()调用。 你也需要保证rand5()应该总是回复O 5,以相等的概率。这是不能接受的是,code偏重,一些额外的0和1。

rand函数 随机数的生成 C语言

如果你认为这是不可能写出这样的功能,那么你就可以让我们都知道,至于为什么它是不可能的。

编辑: 这是我,我认为这是不够的。

  INT rand5()
{
位集&其中3的密度; B:
B [0] = RAND1();
B〔1〕= RAND1();
B〔2〕= RAND1();
INT I = B;
如果(B个= 6)
 返回rand5();
返回我;
}
 

解决方案

不可能的。不能分割2的n次方到6均匀。

Given a function

int rand1();

which return 0 or 1, with equal probability, implement a function

int rand5();

which returns 0,1,2,3,4,5 with equal probability.

!!! Twist !!! Read before marking it as duplicate...

Number of times you can call rand1() is fixed. You may decide it to be 10 or 20 or 100 for that matter, but NOT any number of rand1() calls. i.e. there is a upper limit on on number of rand1() calls. Also you have to guarantee that rand5() should always return o to 5, with equal probability. It is not acceptable that the code is skewed towards, few extra 0 and 1.

If you think it is NOT POSSIBLE to write such function, then you can let us all know, as to why it is not possible.

EDIT : this is what i have, which I think is not sufficient

int rand5()
{
bitset<3> b;
b[0] = rand1();
b[1] = rand1();
b[2] = rand1();
int i = b;
if(b >= 6)
 return rand5();
return i;
}

解决方案

Not possible. You can't divide 2^n into 6 evenly.