php随机分配红包算法 最小支持0.001分配500人

正文开始

[md]


//随机分配红包 protected static function getRandomMoneyList($total, $num) { $sourceMoney = $total; if($num==1) return [$total]; if(strpos($total, '.') !==false) { $array_ = explode('.', $total); $decimal = strlen(end($array_))+1; } else { $decimal = 3; } $beishu = pow(10, $decimal);//放大倍数 运算后再缩小 $bcsub1 = function ($a, $b) use($decimal) { return bcsub($a, $b, $decimal); }; $bcdiv1 = function ($a, $b) use($decimal) { return bcdiv($a, $b, $decimal); }; $bcmul1 = function ($a, $b) use($decimal) { return bcmul($a, $b, $decimal); }; $bcadd1 = function ($a, $b) use($decimal) { return bcadd($a, $b, $decimal); }; $bcMin = function ($a, $b) use($decimal) { return bccomp($a, $b, $decimal) > 0 ? $b : $a; }; $bcMax = function ($a, $b) use($decimal) { return bccomp($a, $b, $decimal) > 0 ? $a : $b; }; // print_r("beishu:".$beishu."\n"); // print_r("decimal:".$decimal."\n"); $total = bcmul($total, $beishu, 2); $max = $bcmul1($total, 0.9); $min = $bcdiv1($bcdiv1($total, $num), 20); // print_r("max:".$max."\n"); // print_r("min:".$min."\n"); $re=[]; $restMoney = $total; while ($num>0){ if($num ==1) { $money = $restMoney; $restMoney= 0; $num--; } else { $vag = $bcdiv1($restMoney, $num);//1.计算红包的平均金额,四舍五入保留两位小数点 // print_r('$vag____'.PHP_EOL); // var_dump($vag); $num --; $tmp_max = $bcMin($max, $bcsub1($restMoney, $bcmul1($num ,$min)));//保证剩下红包金额不小于范围中的最小值 $tmp_min = $bcMax($min, $bcsub1($restMoney, $bcmul1($num, $max)) );//保证剩下红包金额不大于范围中的最大值 $vag_diff = $bcMin($bcsub1($tmp_max, $vag), $bcsub1($vag, $tmp_min));//波动幅度 $end_max = $bcadd1($vag, $vag_diff);//保证剩下红包金额不小于范围中的最小值 $end_min = $bcsub1($vag, $vag_diff); $end_min = (int) ($end_min); //去掉末尾的0 $end_max = (int) ($end_max); //去掉末尾的0 // print_r('$end_min____'.PHP_EOL); // var_dump($end_min); // print_r('$end_max____'.PHP_EOL); // var_dump($end_max); $money = mt_rand($end_min, $end_max); $restMoney = bcsub($restMoney, $money, 20); } $re[] = bcdiv($money, $beishu, $decimal); } shuffle($re); $countTotal = 0; foreach($re as $n=>$v) { $countTotal = $bcadd1($countTotal, $v); } if(bccomp($countTotal, bcadd($sourceMoney, 0, 20), 20) !=0) { print_r('count______:'. $countTotal .'|source:'. $sourceMoney .PHP_EOL); throw new \Exception('分配金额不彻底'); } return $re; }

正文结束

PHP接口(interface)和抽象类(abstract) php遍历阿里云oss文件 批量删除一个目录下的所有文件