WeChat red envelope random algorithm

What I want to write here is one of the WeChat red envelope random algorithms seen on the official account of programmer Xiaohui, the double mean method.

Let the amount of the remaining red envelopes be M, and the number of remaining red envelopes be N, then

The amount of red envelopes grabbed = (0, (M/N) * 2)

That is, if the total amount of red envelopes is 100 and the number is 10, the amount that the first person can grab is (0, (100/10) * 2) that is (0, 20) yuan, the average is 10 yuan,

Suppose the first person grabs 10 yuan, then the amount that the second person can grab is (0, (90/9) * 2) ie (0, 20) yuan, the average is 10 yuan, and so on.

// Red envelope algorithm, the amount parameter is in cents
	public static List<Double> divideRedPackage(Double totalAmount, Integer totalPeopleNum) {

		List<Double> amountList = new ArrayList<>();

		Integer restAmount = (int)(totalAmount*100);

		Integer restPeopleNum = totalPeopleNum;

		Random random = new Random();

		for (int i = 0; i < totalPeopleNum - 1; i++) {

			// Random range: [1, twice the remaining amount per capita), left closed and right open

			int amount = random.nextInt(restAmount / restPeopleNum * 2 - 1) + 1;
			restAmount -= amount;
			restPeopleNum--;
			amountList.add(amount/100.0);
		}
		amountList.add(restAmount/100.0);

		return amountList;
	}

	public static void main(String[] args) {

		List<Double> amountList = divideRedPackage(50.0, 3);
		for (Double amount : amountList) {
			System.out.println(amount);
		}
	}

There is a problem here. The first person who grabs the red packet can only get twice the per capita amount at most, and if the red envelopes grabbed in front are smaller, the later grabbers will be able to grab bigger red envelopes. Randomly give out each red envelope, put it in the list, and then arrange the list randomly

Collections.shuffle(amountList);
In this way, the first person to grab the red envelope may also receive an extra red envelope that is twice the per capita amount.

Guess you like

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