/*
* 按比例分配问题
* 存在N个仓库存放有物品A共计S件,现要求各仓库按库存比例拿出M(M<=S)件物品A,求仓库各余多少件物品A
* 设第n个仓库物品A的库存为Nn
* 各仓库需捐出物品A的件数Pn:round(Nn/S * M)
* 若 M > (P1 + P2 + ... + Pn), 则保证扣减后 Nn >= 0 的前提下,P1++,P2++...直到M = (P1 + P2 + ... + Pn)
* 若 M < (P1 + P2 + ... + Pn), 则保证扣减后 Nn >= 0 的前提下,P1--,P2--...直到M = (P1 + P2 + ... + Pn)
*
* */
function prorate(array $N,int $M)
{
$S = array_sum(array_column($N, 'num'));
if ($S < $M){//不够分配
return false;
}
$per = [];
foreach ($N as $k1=>$v1)
{
$p = round($v1['num']/$S * $M);
$per[$v1['id']] = $v1['num'] < $p ? $v1['num'] : $p;//避免减成负值
}
$perTotal = array_sum($per);
$diff = $perTotal - $M