search
HomeBackend DevelopmentPHP TutorialI wrote a red envelope generation algorithm myself. It can be generated correctly, but it cannot be recursively generated?

Because you want to generate random red envelopes, you need to set the amount, minimum value, maximum value, and quantity of the red envelopes to be distributed.

I tried using a for loop, but it got stuck here in do while, so I wrote one using recursion. The correct red envelope can be generated in the memory, but it cannot be recursed. Please help me to find out where the problem lies?

<code><?php //调试函数
function p($arr)
{
    echo "<pre class="brush:php;toolbar:false">" . print_r($arr, true) . "</code>
"; } //发红包函数 function hongbao($money, $min, $max, $num, $arr = array(), $first = 'yes') { if ($first == 'yes') { //由于红包是以分为单位所以先转换单位,1元=100分,但只需转换一次 $money = $money * 100; $min = $min * 100; $max = $max * 100; //红包发放最大最小值合法性检测,防止发送死循环 if ($money - $min * $num 0) { return "你发放红包的金额太大 这些人领不完"; } } } //计算已生成的红包总额 $safe_total = array_sum($arr); //如果红包总额 大于或等于 要发放的总额, 就说明红包已经生成完毕 if ($safe_total >= $money) { //防止出现 最后出现的数据都相同,所以让这里随机排序一下 shuffle($arr); /*这里有异常, 可以打印出来正确的值 却无法return到最外面吧,应该是递归上的问题*/ p($arr); return $arr; } else { //随机生成红包金额 $rand = mt_rand($min, $max); //用当前的钱 减去已发的钱 -减去本次要发的钱 $zx = $money - $safe_total - $rand - ($num - 1) * $min; $zd = $money - $safe_total - $rand - ($num - 1) * $max; if ($zx >= 0 && $zd

Reply content:

Because you want to generate random red envelopes, you need to set the amount, minimum value, maximum value, and quantity of the red envelopes to be distributed.

I tried using a for loop, but it got stuck here in do while, so I wrote one using recursion. The correct red envelope can be generated in the memory, but it cannot be recursed. Please help me to find out where the problem lies?

<code><?php //调试函数
function p($arr)
{
    echo "<pre class="brush:php;toolbar:false">" . print_r($arr, true) . "</code>
"; } //发红包函数 function hongbao($money, $min, $max, $num, $arr = array(), $first = 'yes') { if ($first == 'yes') { //由于红包是以分为单位所以先转换单位,1元=100分,但只需转换一次 $money = $money * 100; $min = $min * 100; $max = $max * 100; //红包发放最大最小值合法性检测,防止发送死循环 if ($money - $min * $num 0) { return "你发放红包的金额太大 这些人领不完"; } } } //计算已生成的红包总额 $safe_total = array_sum($arr); //如果红包总额 大于或等于 要发放的总额, 就说明红包已经生成完毕 if ($safe_total >= $money) { //防止出现 最后出现的数据都相同,所以让这里随机排序一下 shuffle($arr); /*这里有异常, 可以打印出来正确的值 却无法return到最外面吧,应该是递归上的问题*/ p($arr); return $arr; } else { //随机生成红包金额 $rand = mt_rand($min, $max); //用当前的钱 减去已发的钱 -减去本次要发的钱 $zx = $money - $safe_total - $rand - ($num - 1) * $min; $zd = $money - $safe_total - $rand - ($num - 1) * $max; if ($zx >= 0 && $zd

I changed it according to what you gave:

<?php
//调试函数
function p($arr)
{
    echo "<pre class="brush:php;toolbar:false">" . print_r($arr, true) . "
"; } //发红包函数 function luckymoney($money, $min, $max, $num, $arr = array(), $first = 'yes') { if ($first == 'yes') { //由于红包是以分为单位所以先转换单位,1元=100分,但只需转换一次 $money = $money * 100; $min = $min * 100; $max = $max * 100; //红包发放最大最小值合法性检测,防止发送死循环 if ($money - $min * $num 0) { return "你发放红包的金额太大 这些人领不完"; } } } //计算已生成的红包总额 $safe_total = array_sum($arr); //如果红包总额 大于或等于 要发放的总额, 就说明红包已经生成完毕 if ($num == 1) { // if ($safe_total >= $money) { //防止出现 最后出现的数据都相同,所以让这里随机排序一下 $arr[] = $money - $safe_total; shuffle($arr); /*这里有异常, 可以打印出来正确的值 却无法return到最外面吧,应该是递归上的问题*/ // p($arr); return $arr; } else { //随机生成红包金额 $rand = mt_rand($min, $max); //用当前的钱 减去已发的钱 -减去本次要发的钱 $zx = $money - $safe_total - $rand - ($num - 1) * $min; $zd = $money - $safe_total - $rand - ($num - 1) * $max; if ($zx >= 0 && $zd

Note that since you are using recursion, and it is random based on luck, it is easy for stack overflow,

I tested your data luckymoney(80, 1.3, 2, 50) and it succeeded about 2 times out of 5 times. I suggest you change the algorithm...

return hongbao($money, $min, $max, $num, $arr, 'no');

Thank you everyone, I reused the for loop to improve the algorithm.
Calculated based on sending 200 yuan, minimum 1.3, maximum 3, 200 red envelopes are sent

Using the for loop algorithm, the function is executed 100 times, and the average execution time is 0.004 seconds each time
Using the recursive algorithm, the function is executed 100 times, and the average execution time is 0.211 seconds

The efficiency difference is 52.75 times. Above code. Thank you @aristotll for your suggestion

The following is the for loop code. If you have a better idea, please guide me, thank you

<code><?php //调试函数
function p($arr)
{
    echo "<pre class="brush:php;toolbar:false">" . print_r($arr, true) . "</code>
"; } //发红包函数 function hongbao($money, $min, $max, $num) { $arr = array(); //由于红包是以分为单位所以先转换单位,1元=100分,但只需转换一次 $money = $money * 100; $min = $min * 100; $max = $max * 100; //红包发放最大最小值合法性检测,防止发送死循环 if ($money - $min * $num 0) { return "你发放红包的金额太大 这些人领不完"; } } $tempnum = $num; for ($i = 0; $i = 0 && $zd
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools