One night a few days ago, I suddenly thought that there should be a random algorithm for WeChat red envelopes, so I tried to write them myself, but I didn’t know if it was right. I looked at the statement online. It seemed that the official has not given a definite algorithm so far, so I had to make a fool of myself here and post the code first:
public static double [] getMoney(double money, int num){ Random r = new Random(); DecimalFormat format = new DecimalFormat(".##"); double middle = Double.parseDouble(format.format(money/num)); double [] dou = new double[num]; double redMoney = 0; double nextMoney = money; double sum = 0; int index = 0; for(int i=num;i>0;i--){ if(i == 1){ dou[index] = nextMoney; }else{ while(true){ String str = format.format(r.nextDouble()*nextMoney); redMoney = Double.parseDouble(str); if(redMoney>0 && redMoney < middle){ break; } } nextMoney = Double.parseDouble(format.format(nextMoney - redMoney)); sum = sum + redMoney; dou[index] = redMoney; middle = Double.parseDouble(format.format(nextMoney/(i-1))); index++; } } return dou; }Here is the basic idea: first calculate the average value of the red envelope, and then pass a red envelope with a random number of red envelopes smaller than this average value. After the red envelope is sent, the total amount of the red envelope needs to be reduced accordingly. At the same time, recalculate the average: the new total amount % (original total red envelope number -1), until the last red envelope, put all the remaining amount in.
Thank you for reading, I hope it can help you. Thank you for your support for this site!