php - 在列之间随机分布整数值

标签 php mysql math statistics

我正在制作纸牌游戏,我需要预先创建纸牌并将它们存储在 mysql 表中。我想弄清楚如何制作一个 php 脚本来创建它们。 好吧,有 6 个类别的值,从 0 到 12 不等,每张卡片都有每个类别的值。每张卡片中类别值的总和必须是 36。所以每张卡片是这样的:

  • 6 - 9 - 2 - 10 - 6 - 3

  • 0 - 12 - 0 - 12 - 0 - 12

甚至

  • 6 - 6 - 6 - 6 - 6 - 6

我认为如果我可以随机生成 50 或 60 张卡片,那就太棒了。

提前致谢。

最佳答案

像这样的东西应该可以工作——逻辑可能有点不对劲,我还没有测试过。

function generate_card() {
    $max_card = 12;  // What's the highest value of a card number?
    $min_card = 0;   // What's the lowest value of a card number?
    $num_cards = 6;  // How many numbers on a card?
    $total = 36;     // What's the desired sum?
    $numbers = array();
    $running_total = 0;
    for ($i = 0; $i < $num_cards; ++$i) {
        $max = min($max_card, $total - $running_total); //The highest number we can choose
        $min = max($min_card, $total - $running_total - ($max_card * ($num_cards - ($i + 1)))); //The lowest number we can choose

        //- how much is left ? $total - $running total
        //- min is amount_left - ($max_card

        $number = rand($min, $max);
        $running_total += $number;
        $numbers[] = $number;
    }

    return $numbers;
}

编辑:我错放了一个括号和一个索引,它现在可以正常工作了。

关于php - 在列之间随机分布整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11422953/

相关文章:

php - 如何使用 php 旋转 pdf 文档?

php - 每天统计/计算 mysql 结果

math - 计算给定长度的网格中可能的排列?

php - 使用外键复制 - Laravel

MySql - 三个表由一个表中的一列连接和分组

java - 超过整数最大值的解决方案?

python - 如何在python中计算数值导数的边界点?

php - PDO Firebird 中的异常准备 Magento 集成中的查询

php - 将带连接的 Mysql select 语句转换为多维数组

javascript - Laravel 4 中的 Jquery Ajax - NotFoundHttpException