给定一个函数rand7(),写一个rand10()统一的函数

AGe*_*eek 2 algorithm data-structures

我可以为上述问题找到有效的解决方案....我试图通过这个网站找出问题http://www.ihas1337code.com/2010/11/rejection-sampling.html 但是无法得到理由idx = col +(row-1)*7; 为什么他们乘以7 ...

我们也可以这样做(rand7()*rand7())%10 ...或乘以任何其他数字,因为最后我们必须做mod 10,它只会给10个结果....

为什么他们让解决方案如此困难..请解释一下你的想法......

问题中统一意味着什么?

谢谢..

aio*_*obe 7

(rand7() * rand7()) % 10
Run Code Online (Sandbox Code Playgroud)

不会这样做,因为有些价值观比其他价值更有可能.

让我们比较获得1和获得2的概率:

获得1:

  • rand7() * rand7() 需要等于1,11,21,31或41.
  • 这可以通过以下方式实现:1*1,3*7或7*3.
  • 也就是说,49个中的3个你将获得1

为了得到一个2: ,

  • rand7() * rand7() 需要等于2,12,22,32或42.
  • 这可以通过以下方式实现:1*2,2*1,3*4,4*3,2*6,6*2,6*7,7*6.
  • 也就是说,49次中有8次你会获得2次!

他们的解决方案通过让每个数字(从1到10)同样可能来解决这个问题:每个数字在49个可能的结果中出现4次(9个结果被丢弃并导致重新采样).


事实上,执行Random.nextInt(int n)类似的事情:

int bits, val;
do {
    bits = next(31);
    val = bits % n;
} while (bits - val + (n-1) < 0);    // re-sample until in range.
return val;
Run Code Online (Sandbox Code Playgroud)

这实际上用a rand2来实现一个randN.