Red Envelope Algorithm

Red envelope algorithm
Given a specific number of people and a total amount, everyone gets a share, and everyone’s amount is random. So the allocation has to be limited such that the maximum amount cannot exceed the average value and the minimum amount is 1 cent. The algorithm is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

function moneyBag($number, $money, $min = 1)
{
$max = intval($money / $number);
for ($i = 0; $i < $number; $i++) {
if ($number - 1 == $i) {
$end_arr = $money;
} else {
$one_money =mt_rand($min, $max);
$end_arr = $one_money;
$money -= $end_arr;
$max = intval($money / ($number-($i+1)));
}
yield $end_arr;
}
}
$last_arr = moneyBag(1000, 10 * 100);
$arr = [];
foreach ($last_arr as $end) {
var_dump(bcdiv($end, 100, 2));
}


The final result is as follows:
https://erik.xyz