Recently I was studying the function of sending red envelopes, so I wrote a red envelope generation algorithm.
The requirements of the red envelope generation algorithm
Generate all red envelopes in advance or randomly generate a red envelope with a request
Simply put, it is to decompose a large integer m (directly into units, such as 1 yuan or 100) into n A process of small integers, the range of small integers is [min, max]
The simplest idea is to guarantee the bottom first, each small red envelope is guaranteed to have min, and then each request randomly generates a range from 0 to (max-min). The integer plus min is the amount of the red envelope.
Although this algorithm is simple, it has a drawback: the final red envelope may be min. In other words, the final red envelope may be 0.01 yuan. Another way is to generate all red envelopes in advance, which is easier to control. What I choose is to generate all red envelopes in advance.
The ideal red envelope generation result is that there are more red envelopes near the average value. The number of big red envelopes and small red envelopes is relatively small.
You can imagine that the distribution of the number of generated red envelopes is a bit like a normal distribution.
We need to find a way. Algorithm can improve the probability near the average value. Then use a method of "expansion" and "shrinkage" to achieve this effect.
First square, then generate a random number within the square range, and then take the square root, then the probability will not be the same. It’s average again.
Specific algorithm: (The total amount of money, total number of people, maximum and minimum values set must be reasonable)
Php code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
.
The above introduces the PHP version of PHP random number algorithm for WeChat to randomly generate red envelope amounts, including PHP random number content. I hope it will be helpful to friends who are interested in PHP tutorials.