php随机红包生成算法,随机生成红包金额算法

/**

* 随机生成红包金额

* @param $n 红包个数

* @param $sum 总金额 整数

* @param $index_max 最大金额在数组中索引

* @param $error

* @return array|false

*/

public static function GenRandRePacketsData($n,$sum,&$index_max,&$error)

{

//$n = 20;

//$sum = 300;

if($sum < $n)

{

$error = '金额总数不能小于红包个数'; //$error = '金额总数必须大于红包个数';

return false;

}

if($n > 50)

{

$error = '红包数量不能大于50';

return false;

}

//$sum = $sum * 100;//转为分

$rst = [];

$ave = intval($sum/$n); // 金额除去红包个数 平均值 test:3/3 = 1

$one_rst = rand(1,$ave); // 随机取1到平均值的数

$subSum = $one_rst; // 1

//$rst[] = $one_rst/100;

$rst[] = $one_rst; // $rst = ['0'=>1];

$index_min = 0;

$index_max = 0;

$min = $one_rst; // 1

$max = $one_rst; // 1

for($i = 2; $i <= $n; $i ++)

{

$ave = intval(($sum - $subSum)/($n - $i + 1)); // 1

$one_rst = rand(1,$ave); // 1

if($min > $one_rst) // 1 > 1

{

$min = $one_rst;

$index_min = $i -1;

}

if($max < $one_rst) // 1 < 1

{

$max = $one_rst;

$index_max = $i -1;

}

//$rst[] = $one_rst/100;

$rst[] = $one_rst;

$subSum += $one_rst; // 1

}

$left = $sum - $subSum;

if($left > 0)

{

//$rst[$index_min] = ($rst[$index_min] + $left/100);

$rst[$index_min] = ($rst[$index_min] + $left);

if($rst[$index_min] > $max)

{

$max = $rst[$index_min];

$index_max = $index_min;

}

}

//检测重复的最大值处理,确保最大值唯一

/*for($i =0; $i < $n; $i++)

{

if($rst[$i] === $max && $i !== $index_max)

{

$one_rst = $rst[$i] -1;

$rst[$i] = $one_rst;

$rst[$index_max] = $max + 1;

break;

}

}*/

//重新乱序

shuffle($rst);

//查找最大值

$index_max = 0;

$max = $rst[0];

for($i =1; $i < $n; $i ++)

{

if($rst[$i]> $max)

{

$index_max = $i;

$max = $rst[$i];

}

}

return $rst;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值