为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 创建由 n 个偏移量和最大总和限制的整数值数组

PHP 创建由 n 个偏移量和最大总和限制的整数值数组

PHP
慕的地10843 2021-11-19 15:16:52
正如标题所说......让我们看看代码(更好地解释):$maxItemAmount = 10;$maxItemQtyTotal = 40; $qtyMap = array_map(function () use ($maxItemQtyTotal) {    // returns something with rand()    // but relative to $maxItemQtyTotal}, array_fill(0, $maxItemAmount, null));// expecting: (10 items with a total qty of 40)// [//     // numeric key => qty//     0 => 3, // 3 total//     1 => 4, // 7 total//     2 => 9, // 16 total //     3 => 2, // 18 ...//     4 => 6, // 24//     5 => 1, // 25//     6 => 2, // 27//     7 => 8, // 35//     8 => 3, // 38//     9 => 2, // 40// ]所以我发现了这个很好的“技巧”来在数组中创建偏移量,它允许我使用回调返回值。我现在搜索的是一种返回随机数的方法,但相对于给定的输入$maxItemQtyTotal。另一个例子:$maxItemAmount = 4;$maxItemQtyTotal = 81;// expecting: (4 items with a total qty of 81)// [//     // numeric key => qty//     0 => 11, // 11 total//     1 => 5,  // 16 total//     2 => 42, // 58 total//     3 => 23, // 81 total// ]我不能回来rand(1, $maxItemQtyTotal)。我还得回去rand(1, $n)那里$n是最大数量的最大项目分但仍然是随机的,从最后一个rand(1, $n)添加到下一个还剩下什么?我希望我能描述一下:)
查看完整描述

1 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

我不确定array_fill,但我知道可以通过创建一个带有for循环的简单函数来实现:


function randomNumbers(int $N, int $M): array {

    $nums = [];

    for ($i = 0, $runningTotal = 0; $i < $N - 1; $i++) {

        $ceil = ceil(($M - $runningTotal) / ($N - $i)); // What is the maximum reasonable number we can push into array

        $nums[] = $num = mt_rand(1, $ceil);

        $runningTotal += $num;

    }

    $nums[] = $M - array_sum($nums);

    shuffle($nums); // Randomize elements so that they appear more random

    return $nums;

}

这将生成一个由 N 个随机数组成的数组,这些数加起来为 M。


查看完整回答
反对 回复 2021-11-19
  • 1 回答
  • 0 关注
  • 112 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信