Table of Contents
1 Requirement
2 Requirements Analysis
2.1 Fixed red envelope
2.2 Random red envelope
3 Requirements design
3.1 Class diagram design
3.2 Source code design
3.3 Result display
Home Backend Development PHP Tutorial Detailed explanation of how PHP implements fixed red envelopes and random red envelope algorithms (picture)

Detailed explanation of how PHP implements fixed red envelopes and random red envelope algorithms (picture)

Jul 17, 2017 pm 03:47 PM
php Red envelope

1 Requirement

CleverCode recently received a request to write a fixed red envelope + random red envelope algorithm.

1 Fixed red envelope means that the amount of each red envelope is the same. You can send as many fixed red envelopes as there are.

2 The demand for random red envelopes is. For example, if the total amount of red envelopes is 5 yuan, 10 red envelopes need to be sent. The random range is 0.01 to 0.99; 5 yuan must be paid out, and the amount needs to have a normal distribution with a certain trend. (0.99 can be specified arbitrarily, or it can be avg * 2 - 0.01; for example, avg = 5 / 10 = 0.5; (avg * 2 - 0.01 = 0.99))

2 Requirements Analysis

2.1 Fixed red envelope

If it is a fixed red envelope, the algorithm is a straight line. t is the fixed amount of red envelope. As shown in the picture.
f(x) = t;(1 <= x <= num)


2.2 Random red envelope

If we Use the random function rand. rand(0.01,0.99); then 10 random times, if the worst case scenario is the amount is 0.99, the total amount is 9.9 yuan. It will be more than 5 yuan. Amounts will also not be normally distributed. Finally, I thought about using mathematical functions as a random red envelope generator. Parabolas and trigonometric functions can be used. Finally, the isosceles trigonometric linear function was selected.

1 Algorithm principle

If the total amount of red envelopes to be issued is totalMoney, the number of red envelopes is num, and the amount range is [min,max], the linear equation is as shown in the figure .


Coordinates of three points:

(x1,y1) =  (1,min)
  (x2,y2)  = (num/2,max)
  (x3,y3) = (num,min)
Copy after login

Determined linear equation:

$y = 1.0 * ($x - $x1) / ($x2 - $x1) * ($y2 - $y1) + $y1 ; (x1 <= x <= x2)
$y = 1.0 * ($x - $x2) / ($x3 - $x2) * ($y3 - $y2) + $y2;  (x2 <= x <= x3)
Copy after login

Revised data:
y (Total) = y1 + y2 + y3 +... ynum;
y (Total) may be > totalMoney, indicating that the generated amount is too much and the data needs to be revised, then start from (y1, y2, y3. ....ynum) These are reduced by 0.01 each time. Until y(total) = totalMoney.
y (together) may be < totalMoney, indicating that the generated amount is less and the data needs to be revised, then add 0.01 each time from (y1, y2, y3...ynum). Until y(total) = totalMoney.

2 Algorithm Principle Example

If the total amount of red envelopes to be issued is 11470, the number of red envelopes is 7400, and the amount range is [0.01,3.09] , the linear equation is shown in the figure.


3 Requirements design

3.1 Class diagram design


3.2 Source code design

<?php
/**
 * 随机红包+固定红包算法[策略模式]
 * copyright (c) 2016 http://blog.csdn.net/CleverCode
 */

//配置传输数据DTO
class OptionDTO
{/*{{{*/

    //红包总金额
    public $totalMoney;

    //红包数量
    public $num;

    //范围开始
    public $rangeStart;

    //范围结算
    public $rangeEnd;

    //生成红包策略
    public $builderStrategy;

    //随机红包剩余规则
    public $randFormatType; //Can_Left:不修数据,可以有剩余;No_Left:不能有剩余

    public static function create($totalMoney,$num,$rangeStart,$rangEnd,
        $builderStrategy,$randFormatType = &#39;No_Left&#39;)
    {/*{{{*/
        $self = new self();
        $self->num = $num;
        $self->rangeStart = $rangeStart;
        $self->rangeEnd = $rangEnd;
        $self->totalMoney = $totalMoney;
        $self->builderStrategy = $builderStrategy;
        $self->randFormatType = $randFormatType;
        return $self; 
    }/*}}}*/

}/*}}}*/

//红包生成器接口
interface IBuilderStrategy
{/*{{{*/
    //创建红包
    public function create();    
    //设置配置
    public function setOption(OptionDTO $option); 
    //是否可以生成红包
    public function isCanBuilder();
    //生成红包函数
    public function fx($x);
}/*}}}*/

//固定等额红包策略
class EqualPackageStrategy implements IBuilderStrategy
{/*{{{*/
    //单个红包金额
    public $oneMoney;

    //数量
    public $num;

    public function construct($option = null) 
    {
        if($option instanceof OptionDTO)
        {
            $this->setOption($option);
        }
    }

    public function setOption(OptionDTO $option)
    {
        $this->oneMoney = $option->rangeStart;
        $this->num = $option->num;
    }

    public function create() 
    {/*{{{*/

        $data = array();
        if(false == $this->isCanBuilder())
        {
            return $data;    
        }

        $data = array();
        if(false == is_int($this->num) || $this->num <= 0) 
        {
            return $data;    
        }
        for($i = 1;$i <= $this->num;$i++)
        {
            $data[$i] = $this->fx($i);
        }
        return $data;
    }/*}}}*/
    
    /**
     * 等额红包的方程是一条直线 
     * 
     * @param mixed $x 
     * @access public
     * @return void
     */
    public function fx($x) 
    {/*{{{*/
        return $this->oneMoney; 
    }/*}}}*/

    /**
     * 是否能固定红包 
     * 
     * @access public
     * @return void
     */
    public function isCanBuilder()
    {/*{{{*/
        if(false == is_int($this->num) || $this->num <= 0) 
        {
            return false;    
        }

        if(false ==  is_numeric($this->oneMoney) || $this->oneMoney <= 0)
        {
            return false;
        }

        //单个红包小于1分
        if($this->oneMoney < 0.01)
        {
            return false;
        }
        
        return true;

    }/*}}}*/


}/*}}}*/

//随机红包策略(三角形)
class RandTrianglePackageStrategy implements IBuilderStrategy
{/*{{{*/
    //总额
    public $totalMoney;

    //红包数量
    public $num;

    //随机红包最小值
    public $minMoney;

    //随机红包最大值
    public $maxMoney;

    //修数据方式:NO_LEFT: 红包总额 = 预算总额;CAN_LEFT: 红包总额 <= 预算总额
    public $formatType; 

    //预算剩余金额
    public $leftMoney;


    public function construct($option = null) 
    {/*{{{*/
        if($option instanceof OptionDTO)
        {
            $this->setOption($option);
        }
    }/*}}}*/

    public function setOption(OptionDTO $option)
    {/*{{{*/
        $this->totalMoney = $option->totalMoney;
        $this->num = $option->num;
        $this->formatType = $option->randFormatType;
        $this->minMoney = $option->rangeStart;
        $this->maxMoney = $option->rangeEnd;
        $this->leftMoney = $this->totalMoney;
    }/*}}}*/

    /**
     * 创建随机红包 
     * 
     * @access public
     * @return void
     */
    public function create() 
    {/*{{{*/
        
        $data = array();
        if(false == $this->isCanBuilder())
        {
            return $data;    
        }
        
        $leftMoney = $this->leftMoney;
        for($i = 1;$i <= $this->num;$i++)
        {
            $data[$i] = $this->fx($i);
            $leftMoney = $leftMoney - $data[$i]; 
        }

        //修数据
        list($okLeftMoney,$okData) = $this->format($leftMoney,$data);

        //随机排序
        shuffle($okData);
        $this->leftMoney = $okLeftMoney;

        return $okData;
    }/*}}}*/

    /**
     * 是否能够发随机红包 
     * 
     * @access public
     * @return void
     */
    public function isCanBuilder()
    {/*{{{*/
        if(false == is_int($this->num) || $this->num <= 0) 
        {
            return false;    
        }

        if(false ==  is_numeric($this->totalMoney) || $this->totalMoney <= 0)
        {
            return false;
        }

        //均值
        $avgMoney = $this->totalMoney / 1.0 / $this->num;
        
        //均值小于最小值
        if($avgMoney < $this->minMoney )
        {
            return false;
        }
        
        return true;

    }/*}}}*/

    /**
     * 获取剩余金额 
     * 
     * @access public
     * @return void
     */
    public function getLeftMoney()
    {/*{{{*/
        return $this->leftMoney;
    }/*}}}*/

    /**
     * 随机红包生成函数。三角函数。[(1,0.01),($num/2,$avgMoney),($num,0.01)] 
     * 
     * @param mixed $x,1 <= $x <= $this->num; 
     * @access public
     * @return void
     */
    public function fx($x)
    {/*{{{*/
        
        if(false == $this->isCanBuilder())
        {
            return 0;
        }

        if($x < 1 || $x > $this->num)
        {
            return 0;
        }
        
        $x1 = 1;
        $y1 = $this->minMoney;
        
        //我的峰值
        $y2 = $this->maxMoney;

        //中间点
        $x2 = ceil($this->num /  1.0 / 2);

        //最后点
        $x3 = $this->num;
        $y3 = $this->minMoney;  

        //当x1,x2,x3都是1的时候(竖线)
        if($x1 == $x2 && $x2 == $x3)
        {
            return $y2;
        }

        // &#39;/_\&#39;三角形状的线性方程
        //&#39;/&#39;部分
        if($x1 != $x2 && $x >= $x1 && $x <= $x2)
        {

            $y = 1.0 * ($x - $x1) / ($x2 - $x1) * ($y2 - $y1) + $y1;  
            return number_format($y, 2, &#39;.&#39;, &#39;&#39;);
        }

        //&#39;\&#39;形状
        if($x2 != $x3 && $x >= $x2 && $x <= $x3)
        {

            $y = 1.0 * ($x - $x2) / ($x3 - $x2) * ($y3 - $y2) + $y2;  
            return number_format($y, 2, &#39;.&#39;, &#39;&#39;);
        }
        
        return 0;


    }/*}}}*/

    /**
     * 格式化修红包数据 
     * 
     * @param mixed $leftMoney 
     * @param array $data 
     * @access public
     * @return void
     */
    private function format($leftMoney,array $data)
    {/*{{{*/

        //不能发随机红包
        if(false == $this->isCanBuilder())
        {
            return array($leftMoney,$data);  
        }
        
        //红包剩余是0
        if(0 == $leftMoney)
        {
            return array($leftMoney,$data);  
        }

        //数组为空
        if(count($data) < 1)
        {
            return array($leftMoney,$data);  
        }

        //如果是可以有剩余,并且$leftMoney > 0
        if(&#39;Can_Left&#39; == $this->formatType
          && $leftMoney > 0)
        {
            return array($leftMoney,$data);  
        }


        //我的峰值
        $myMax = $this->maxMoney;

        // 如果还有余钱,则尝试加到小红包里,如果加不进去,则尝试下一个。
        while($leftMoney > 0)
        {
            $found = 0;
            foreach($data as $key => $val) 
            {
                //减少循环优化
                if($leftMoney <= 0)
                {
                    break;
                }

                //预判
                $afterLeftMoney =  (double)$leftMoney - 0.01;
                $afterVal = (double)$val + 0.01;
                if( $afterLeftMoney >= 0  && $afterVal <= $myMax)
                {
                    $found = 1;
                    $data[$key] = number_format($afterVal,2,&#39;.&#39;,&#39;&#39;);
                    $leftMoney = $afterLeftMoney;
                    //精度
                    $leftMoney = number_format($leftMoney,2,&#39;.&#39;,&#39;&#39;);
                }
            }

            //如果没有可以加的红包,需要结束,否则死循环
            if($found == 0)
            {
                break;
            }
        }
        //如果$leftMoney < 0 ,说明生成的红包超过预算了,需要减少部分红包金额
        while($leftMoney < 0)
        {
            $found = 0;
            foreach($data as $key => $val) 
            {
                if($leftMoney >= 0)
                {
                    break; 
                }
                //预判
                
                $afterLeftMoney =  (double)$leftMoney + 0.01;
                $afterVal = (double)$val - 0.01;
                if( $afterLeftMoney <= 0 && $afterVal >= $this->minMoney)
                {
                    $found = 1;
                    $data[$key] = number_format($afterVal,2,&#39;.&#39;,&#39;&#39;);
                    $leftMoney = $afterLeftMoney;
                    $leftMoney = number_format($leftMoney,2,&#39;.&#39;,&#39;&#39;);
                }
            }
            
            //如果一个减少的红包都没有的话,需要结束,否则死循环
            if($found == 0)
            {
                break;
            }
        }
        return array($leftMoney,$data);  
    }/*}}}*/

}/*}}}*/

//维护策略的环境类
class RedPackageBuilder
{/*{{{*/

    // 实例  
    protected static $_instance = null;  

    /** 
     * Singleton instance(获取自己的实例) 
     * 
     * @return MemcacheOperate 
     */  
    public static function getInstance()
    {  /*{{{*/
        if (null === self::$_instance) 
        {  
            self::$_instance = new self();  
        }  
        return self::$_instance;  
    }  /*}}}*/

    /** 
     * 获取策略【使用反射】
     * 
     * @param string $type 类型 
     * @return void 
     */  
    public function getBuilderStrategy($type)
    {  /*{{{*/
        $class = $type.&#39;PackageStrategy&#39;;

        if(class_exists($class))
        {
            return new $class();  
        }
        else
        {
            throw new Exception("{$class} 类不存在!");
        }
    }  /*}}}*/

    public function getRedPackageByDTO(OptionDTO $optionDTO) 
    {/*{{{*/
        //获取策略
        $builderStrategy = $this->getBuilderStrategy($optionDTO->builderStrategy);

        //设置参数
        $builderStrategy->setOption($optionDTO);

        return $builderStrategy->create();
    }/*}}}*/
    
}/*}}}*/

class Client
{/*{{{*/
    public static function main($argv)
    {
        //固定红包
        $dto = OptionDTO::create(1000,10,100,100,&#39;Equal&#39;);
        $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
        //print_r($data);

        //随机红包[修数据]
        $dto = OptionDTO::create(5,10,0.01,0.99,&#39;RandTriangle&#39;);
        $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
        print_r($data);

        //随机红包[不修数据]
        $dto = OptionDTO::create(5,10,0.01,0.99,&#39;RandTriangle&#39;,&#39;Can_Left&#39;);
        $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
        //print_r($data);
        
    }
}/*}}}*/

Client::main($argv);
Copy after login

3.3 Result display

1 Fixed red envelope

//固定红包
$dto = OptionDTO::create(1000,10,100,100,&#39;Equal&#39;);
$data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
print_r($data);
Copy after login


2 Random red envelope (data modification)

The random sorting function of PHP is used here, shuffle($okData), so the result you see is not linear, this result is more random.

//随机红包[修数据]
 $dto = OptionDTO::create(5,10,0.01,0.99,&#39;RandTriangle&#39;);
 $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
 print_r($data);
Copy after login


3 Random red envelope (no data modification)

No data modification, the amount of 1 and num is the minimum Value 0.01.

//随机红包[不修数据]
 $dto = OptionDTO::create(5,10,0.01,0.99,&#39;RandTriangle&#39;,&#39;Can_Left&#39;);
 $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
 print_r($data);
Copy after login



The above is the detailed content of Detailed explanation of how PHP implements fixed red envelopes and random red envelope algorithms (picture). For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles