给定一个随机数生成器,用它来创建一个新生成器

时间:2013-02-16 03:04:34

标签: data-structures random puzzle

给定一个生成1到5之间随机数的函数F,我如何使用F编写函数G来生成1到7之间的随机数?

G生成的每个数字的概率应该相同。

到目前为止,我已经尝试了等式G=F + (5*(F/7)),尽管我不确定所有概率是否相同。

1 个答案:

答案 0 :(得分:0)

伪代码:

function g()
    repeat
        // result will be equidistributed in 0..24
        result = (f()-1)*5 + (f()-1);
        // wait till we have something below 21, on average this happens 21 out of 25 times in the first pass
        if (result < 21): return 1 + (result % 7)