随机数生成器的组合

发布于 2024-09-27 09:10:24 字数 136 浏览 1 评论 0原文

给定两个随机整数生成器,一个生成 1 到 7 之间的值,另一个生成 1 到 5 之间的值,如何制作一个生成 1 到 13 之间的随机整数生成器?我尝试过以各种方式解决这个问题,但我一直无法想出一个以相等或接近相等的概率生成从 1 到 13 的数字的解决方案。

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 near equal probability.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唔猫 2024-10-04 09:10:24

使用将随机范围从 1–5 扩展到 1–7 的前两个答案,我得出了以下结论。可能有一种更有效的方法来做到这一点(也许使用 1-5 生成器?)但这似乎可行。

针对紧凑性进行了优化

    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;

针对可理解性进行了优化

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];
}

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];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文