写一个 C++给定 rand1() 生成 0 到 5 之间的随机分布的程序,随机返回 0 或 1
函数
int rand1();
给定一个以相同概率返回 0 或 1 的 , 实现一个
int rand5();
以相等概率返回 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可能。你不能将 2^n 整分为 6。
Not possible. You can't divide 2^n into 6 evenly.
这就是人们在从 [0, 1) 范围内的随机浮点数生成 [0, N) 范围内的随机整数时所做的事情(无论他们是否知道):
我怀疑这不会产生完全均匀分布,但对于大多数用途来说已经足够了。
This is what people are doing (whether they know it or not) when they generate a random integer in the range [0, N) from a random floating-point number in the range [0, 1):
I suspect this does not produce a perfectly uniform distribution, but it's good enough for most purposes.