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

正如标题所说......让我们看看代码(更好地解释):


$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)添加到下一个还剩下什么?


我希望我能描述一下:)


慕的地10843
浏览 113回答 1
1回答

慕森王

我不确定array_fill,但我知道可以通过创建一个带有for循环的简单函数来实现:function randomNumbers(int $N, int $M): array {&nbsp; &nbsp; $nums = [];&nbsp; &nbsp; for ($i = 0, $runningTotal = 0; $i < $N - 1; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $ceil = ceil(($M - $runningTotal) / ($N - $i)); // What is the maximum reasonable number we can push into array&nbsp; &nbsp; &nbsp; &nbsp; $nums[] = $num = mt_rand(1, $ceil);&nbsp; &nbsp; &nbsp; &nbsp; $runningTotal += $num;&nbsp; &nbsp; }&nbsp; &nbsp; $nums[] = $M - array_sum($nums);&nbsp; &nbsp; shuffle($nums); // Randomize elements so that they appear more random&nbsp; &nbsp; return $nums;}这将生成一个由 N 个随机数组成的数组,这些数加起来为 M。
打开App,查看更多内容
随时随地看视频慕课网APP