search
HomeBackend DevelopmentPHP TutorialShare ideas for implementing PHP red envelope algorithm (with development code attached)

根据很多需求的使用场景,如发红包、砍价类需求,这两个功能都有一个同样的特点,如下:

红包

1.Total amount
2.Number of red envelopes
3.Min. Number of red envelopes

Bargaining

1. Total bargaining amount
2. How many people are needed to complete the bargaining (the number of people depends on the demand)

  • Fixed Number of Bargaining Numbers
  • Random Bargaining Number of Numbers
  • Specified Random Bargaining Number of People
    Point 2: The three rules all need to determine a number of people according to the rules

3. Minimum bargaining amount

Development ideas

Verification parameters

The minimum amount is not allowed to be less than 0
Total The amount is not allowed to be greater than the quantity multiplied by the minimum amount

Distribution amount

Get the average amount (total amount/remaining quantity)

Distribution amount Average amountless than or equal to Directly allocate the minimum amount when the maximum amount is reached
Get the amount Amplitude ratio The minimum value is not allowed to be less than -1 The maximum value is not allowed to be greater than 1
Obtained Distribution amount amplitude calculation (average * (1 amplitude ratio))
Distribution amount judgmentDistribution amountis less than minimum amountordistribution amount is greater than The maximum amount that can be claimed ((minimum amount remaining total amount) - (remaining quantity × minimum amount)) will redistribute the amount
If the last one is left, all the remaining amounts will be distributed

Development code

<?php /**
 * 发送红包
 * Class sandRed
 */
class sandRed
{
    #红包金额
    protected $amount;
    #红包个数
    protected $num;
    #领取的红包最小金额
    protected $minAmount;
    #红包分配结果
    protected $amountArr = [];

    public function __construct($amount, $num = 1, $minAmount = 1)
    {
        $this->amount = $amount;
        $this->num = $num;
        $this->minAmount = $minAmount;
    }

    /**
     * 处理返回
     * @return array
     * @throws Exception
     */
    public function handle()
    {
        # 验证
        if ($this->amount minAmount * $this->num) {
            throw new Exception('红包总金额必须≥'.$validAmount.'元');
        }
        # 分配红包
        $this->allot();
        return $this->amountArr;
    }

    /**
     * 分配红包
     */
    protected function allot()
    {
        # 剩余可分配的红包个数
        $num = $this->num;

        # 剩余可领取的红包金额
        $amount = $this->amount;
        while ($num >= 1) {
            if ($num == 1) {
                # 剩余一个的时候,直接取剩余红包
                $coupon_amount = $this->formattingAmount($amount);
            } else {

                # 平均金额
                $avgAmount = $this->formattingAmount($amount / $num);

                # 分配金额
                $countAllotAmount = $this->countAllotAmount($avgAmount, $amount, $num);

                # 剩余的红包的平均金额
                $coupon_amount = $this->formattingAmount($countAllotAmount);
            }
            # 追加分配金额
            $this->amountArr[] = $coupon_amount;

            # 计算剩余金额
            $amount -= $coupon_amount;

            $num--;
        }
        # 随机打乱
        // shuffle($this->amountArr);
    }

    /**
     * 计算分配的红包金额
     * @param float $avgAmount 每次计算的平均金额
     * @param float $amount 剩余可领取金额
     * @param int $num 剩余可领取的红包个数
     * @return float
     */
    protected function countAllotAmount($avgAmount, $amount, $num)
    {
        # 如果平均金额小于等于最低金额,则直接返回最低金额
        if ($avgAmount minAmount) {
            return $this->minAmount;
        }
        # 浮动比率
        $floatingRate = $this->floatingRate();

        # 分配金额
        $allotAmount = $avgAmount * (1 + $floatingRate);

        # 浮动计算
        $coupon_amount = $this->formattingAmount($allotAmount);

        # 如果低于最低金额或超过可领取的最大金额,则重新获取
        if ($coupon_amount minAmount || $coupon_amount > $this->canReceiveMaxAmount($amount, $num)) {
            return $this->countAllotAmount($avgAmount, $amount, $num);
        }
        return $coupon_amount;
    }

    /**
     * 计算分配的红包金额-可领取的最大金额
     * @param $amount
     * @param $num
     * @return float|int
     */
    protected function canReceiveMaxAmount($amount, $num)
    {
        return $this->minAmount + $amount - $num * $this->minAmount;
    }

    /**
     * 红包金额浮动比例
     * @return float|int
     */
    protected function floatingRate()
    {
        # 60%机率获取剩余平均值的大幅度红包(可能正数、可能负数)
        if (rand(1, 100) 
  • Total amount
$amount = 1;
  • Allocation quantity
$num = 10;
  • Minimum amount
$minAmount = 0.01;

$red = new sandRed($amount, $num, $minAmount);

$res = $red->handle();
print_r($res);
  • Output result [0.10,0.04,0.08,0.04,0.16,0.14,0.11,0.13,0.11,0.09]
echo array_sum($res);
  • Output result 1

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Share ideas for implementing PHP red envelope algorithm (with development code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.