开发者

Combination of Random Number Generators

Given two random integer generators one that generates between 1 and 7 and another that generates between 1 and 5, how do you make a random integer generator that generates between 1 and 13? I have tried solving this question in various ways but I have not been able to come up with a solution that generates numbers from 1 to 13 with equal or nea开发者_C百科r equal probability.


Using the top two answers for Expand a random range from 1–5 to 1–7, I've come up with the following. There's probably a more efficient way to do this (maybe using the 1-5 generator?) but this seems to work.

Optimized for Compactness

    var j;
    do {
        j = 7 * (rand7() - 1) + rand7();  // uniformly random between 1 and 49
    } while (j > 39);
    // j is now uniformly random between 1 and 39 (an even multiple of 13)
    j = j % 13 + 1;

Optimized for understandability

var v = [
    [1,  2,  3,  4,  5,  6,  7],
    [8,  9, 10, 11, 12, 13,  1],
    [2,  3,  4,  5,  6,  7,  8],
    [9, 10, 11, 12, 13,  1,  2],
    [3,  4,  5,  6,  7,  8,  9],
    [10, 11, 12, 13, 0,  0,  0],
    [0,  0,  0,  0,  0,  0,  0]
];
var j = 0;
while (j == 0) {
    j = v[rand7() - 1][rand7() - 1];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜