Home>Article>Backend Development> Brief analysis of PHP red envelope opening algorithm

Brief analysis of PHP red envelope opening algorithm

藏色散人
藏色散人 forward
2021-06-09 15:02:02 4536browse

This article will give you a brief analysis of the PHP red envelope opening algorithm. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

PHP Red Packet Splitting Algorithm

The code is as follows:

/** * 拆分红包 * @param SendRedPackageRequest $request * @return array */ protected function spitMoney(SendRedPackageRequest $request) { $result = []; $reamingMoney = $request->money; for ($i = $request->count; $i >= 1; $i--) { if ($i === 1) { $result[] = round($reamingMoney, 2); $reamingMoney = 0; } else { $average = round(bcdiv($reamingMoney, $i), 2); //平均值 $amount = round(mt_rand(1, $average * 199) / 100, 2); $reamingMoney = doubleval(bcsub($reamingMoney, $amount)); $result[] = round($amount, 2); } } return $result; }

The logic is relatively simple, input the amount and the number of splits

First cycle through the number to be split, and if it is the last one, put all the remaining money into it;

If not, take the remaining amount (the remaining amount in the first cycle = total amount ) divided by the remaining times to get the average, then randomly pick the smallest 0.01 and the average * 2, and just update the remaining amount.

The algorithm simulates the WeChat red envelope splitting algorithm, but this is calculated and saved in advance, and WeChat calculates it dynamically each time.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Brief analysis of PHP red envelope opening algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete