Brief analysis of PHP red envelope opening algorithm

藏色散人
Release: 2023-04-10 07:58:02
forward
4597 people have browsed it

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;
    }
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!