How is the random algorithm of wechat red packet implemented?

I see such a problem in Zhihu How is the random algorithm of wechat red packet implemented?

Some people say that Tencent is basically achieved in this way:

public static double getRandomMoney(LeftMoneyPackage _leftMoneyPackage) {
    // Remansize remaining number of red packets
    // remainMoney
    if (_leftMoneyPackage.remainSize == 1) {
        return (double) Math.round(_leftMoneyPackage.remainMoney * 100) / 100;
    Random r     = new Random();
    double min   = 0.01; //
    double max   = _leftMoneyPackage.remainMoney / _leftMoneyPackage.remainSize * 2;
    double money = r.nextDouble() * max;
    money = money <= min ? 0.01: money;
    money = Math.floor(money * 100) / 100;
    _leftMoneyPackage.remainMoney -= money;
    return money;

There are also people who have done the distribution of positive and negative, analysis of variance, regression analysis, statistical simulation and so on. If the graph is too long, I will not paste it.


  1. All the answers are "random when taking", that is to say, design the concept of "red packet pool", and then take random numbers when taking.
  2. All the answers are "random money", that is, random amount, and then return.

Now let's change our thinking. Now let's change all our money into 1 cent coins, think of red envelopes as cans, and then scatter coins.

 * @param count Number of red packets
 * @param money Total amount
 * @return
public static Integer[] ranRedPac(Integer count, Integer money) {
	Integer[] result = new Integer[count];
	for (int i = 1; i <= money; i++) {
		int n = new Random().nextInt(count);
		result[n] = result[n] == null ? 1 : result[n] + 1;
	return result;

public static void main(String[] args) {
	Arrays.asList(ranRedPac(10, 5000000)).forEach(i -> System.out.println(i));
	System.out.println("sum: " + Arrays.asList(ranRedPac(10, 50)).stream().mapToInt(i -> i).sum());

Choose red envelopes at random for each cent.

As for what regression analysis, statistical simulation is useless.

In this example, we abandon the traditional concepts of "sampling" and "random amount", so that money has the sense of choice and performs the "random" behavior, and naturally the red packet has the attribute of random amount.

Change your mind. Don't complicate simple problems.

When we design code, we usually consider the logic in real life, and abstract objects into classes and behaviors into methods. But occasionally we have to think about a reversal of thinking.

Of course, my code has some drawbacks.

Thinking is the most important thing.

Tags: Attribute

Posted on Tue, 05 May 2020 05:11:08 -0400 by vB3Dev.Com