Today I went to an interview. At the end, the interviewer asked how random red envelope distribution is implemented. I really had never done that, and couldn’t come up with it either. Afterwards I looked into it myself and found it’s no big deal..
Reference article https://www.cnblogs.com/dreign/p/4610766.html
It gave me a normal distribution based method; after comparing it with several others back and forth, I ended up choosing this one.
Let’s analyze the requirements as follows:
A user sends a 100 yuan red envelope split into 100 shares. So each share has a random amount. And the sum of the 100 shares must be exactly 100 yuan. First of all, then, each user gets at least 0.01 yuan. The largest red envelope a user can get is the total amount minus the amount already handed out, averaged over the remaining users.
Once you see that, it’s clear. So every random amount you draw must lie between the minimum amount and the maximum amount.
Let’s try some code.
Suppose there are 100 yuan to be given out to 100 people, with 100 red envelopes generated randomly. The code is as follows:

Output result


