How is the random algorithm of WeChat red envelopes implemented?

I saw such a question on Zhihu. How is the random algorithm of WeChat red envelopes implemented?

Some people say that Tencent is roughly implemented like this:

public static double getRandomMoney(LeftMoneyPackage _leftMoneyPackage) {
    // remainSize 剩余的红包数量
    // remainMoney 剩余的钱
    if (_leftMoneyPackage.remainSize == 1) {
        _leftMoneyPackage.remainSize--;
        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.remainSize--;
    _leftMoneyPackage.remainMoney -= money;
    return money;
}

Some people have also done normal distribution, analysis of variance, regression analysis, statistical simulation, etc., and I will not post the picture if it is too long.

However

  1. All the answers are "random when taken", that is, the concept of "red envelope pool" is designed, and then random numbers are taken when drawing.
  2. All answers are "random of money", i.e. a random amount, and return.

Let's change the way of thinking. Now we change all the money into 1 cent coins , think of the red envelope as a jar , and then throw coins .

/**
 * @param count 红包数
 * @param money 总金额
 * @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());
}

Red envelopes are randomly selected for every penny.

As for regression analysis, statistical simulation is not used at all .

In this example, we abandon the traditional concepts of "extraction" and "random amount", so that money has a sense of choice and performs "random" behavior. Naturally, the red envelope has the attribute of random amount.

Change your thinking, don't complicate simple problems.

When we code and design, we usually consider the logic in real life, and abstract objects into classes and behaviors into methods. However, we also occasionally consider mind reversal .

Of course, my code has certain drawbacks.

Thinking is the most important thing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325435706&siteId=291194637