php砍价算法
作者:互联网
/** * 砍价算法-生成砍价金额 * * @author 宋健安<506780989@qq.com> * * @param int $people 砍价人数或次数 * @param int $amount 砍价总额 * @param int $min 最低砍价金额 不得低于0 * @param int $max 最高砍价金额 砍价次数 * 最高砍价金额不得小于砍价总额 * @param int $level 层级 防止递归超出限制 * * @return array */ function genRandomAmount($people = 0, $totalAmount = 0, $min = 0, $max = 0, $level = 1) { // 防止递归超出限制报异常,提前退出 if ($level == 200) { return []; } $arr = []; if (empty($people) || empty($totalAmount)) { return []; } $tmpTotal = $totalAmount * 100; $tmpMin = $min * 100; $tmpMax = $max * 100; for ($i = 0; $i < $people - 1; $i++) { $arr[$i] = mt_rand($tmpMin, $tmpMax); $tmpTotal = $tmpTotal - $arr[$i]; } $arr[$people - 1] = $tmpTotal; if ($tmpTotal < $tmpMin || $tmpTotal > $tmpMax) { return genRandomAmount($people, $totalAmount, $min, $max, $level + 1); } return array_map(function ($value) { return $value / 100; }, $arr); } /** * 砍价算法-获取砍价金额 * * @author 宋健安<506780989@qq.com> * * @param int $people 砍价人数或次数 * @param int $amount 砍价总额 * @param int $min 最低砍价金额 不得低于0 * @param int $max 最高砍价金额 砍价次数 * 最高砍价金额不得小于砍价总额 * * @return array */ function getRandomAmount($people = 0, $totalAmount = 0, $min = 0, $max = 0) { if ($people * $max <= $totalAmount) { return false; } $arr = genRandomAmount($people, $totalAmount, $min, $max); // 有几率会因为递归调用超出限制而返回空数组,这里继续重新生成,直到金额正确 while (empty($arr)) { $arr = genRandomAmount($people, $totalAmount, $min, $max); } return $arr; }
技术交流群: 109345266
标签:return,people,int,max,算法,param,砍价,php 来源: https://www.cnblogs.com/nonsec/p/12122900.html