Implementing WeChat Red Packet Random Distribution in PHP
This article explores the logic behind WeChat's red‑packet random algorithm, outlines the required constraints, and provides step‑by‑step PHP code that generates fair, varied payouts for a fixed total amount among multiple recipients.
Inspired by a spontaneous red‑packet giveaway in a WeChat alumni group, the author investigates how WeChat distributes a total of 10 CNY among 28 random recipients.
The discussion references a popular Zhihu post about the algorithm but notes the lack of official details.
Key Requirements for the Algorithm
Every participant must receive some amount.
The sum of all received amounts must equal the total amount.
Amounts should vary but not be excessively disparate.
The algorithm must remain simple.
Before coding, a progressive model is built to understand the pattern.
<code>Set total = 10 CNY, N participants receive randomly: N=1: amount = X N=2: first amount = random(0.01, 9.99), second = total - first N=3: first = random(0.01, 0.98) second = random(0.01, total - first - 0.01) third = total - first - second ... (continue similarly for larger N)</code>
Initial implementation uses a simple random bound:
<code>header("Content-Type: text/html;charset=utf-8"); $total = 10; // total amount $num = 8; // number of red packets $min = 0.01; // minimum per person for ($i = 1; $i < $num; $i++) { $safe_total = $total - ($num - $i) * $min; // safe upper bound $money = mt_rand($min * 100, $safe_total * 100) / 100; $total -= $money; echo "Packet $i: $money 元, remaining: $total 元<br/>"; } echo "Packet $num: $total 元, remaining: 0 元"; </code>
This version produces large fluctuations, making the distribution uninteresting.
To reduce variance, the safe upper bound is adjusted to the average of the remaining amount:
<code>header("Content-Type: text/html;charset=utf-8"); $total = 10; $num = 8; $min = 0.01; for ($i = 1; $i < $num; $i++) { $safe_total = ($total - ($num - $i) * $min) / ($num - $i); $money = mt_rand($min * 100, $safe_total * 100) / 100; $total -= $money; echo "Packet $i: $money 元, remaining: $total 元<br/>"; } echo "Packet $num: $total 元, remaining: 0 元"; </code>
The improved algorithm yields more balanced results, as shown in the output screenshot.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
