今天看见一篇文章说微信红包的算法,大致是说微信红包的金额是随机生成的,而且是在最小0.01 到 剩余平均值 * 2之间. 感觉挺有意思的, 我用php的代码初步实现下.
class hongbao{
public $size;
public $money;
public function __construct($size=10, $money=100){
$this->size = $size;
$this->money = $money;
}
}
class suanfa{
public static function weixin_hongbao(hongbao $hongbao){
$result = array();
while ($hongbao->size) {
if ($hongbao->size == 1){
// 最后一个就不用随机了
--$hongbao->size;
$result[] = $hongbao->money;
return $result;
}
// 最小金额
$min = 0.01;
// round是为了让数据好看点,毕竟浮点数运算不准确
$max = $hongbao->money / $hongbao->size *2;
$money = mt_rand(1, $max * 100) / 100;
$money = round( $money <= $min ? $min : $money, 2);
--$hongbao->size;
$hon