微信红包随机算法

这里要写的是,在程序员小灰的公众号上看到的微信红包随机算法中的一个,二倍均值法。

设剩余的红包金额为M,剩余的红包数量为N,那么

抢到的红包金额 = (0,(M/N)* 2)

即若红包总额为100,数量为10,第一个人可以抢到的金额为(0 , (100/10)* 2)即(0 , 20)元,平均值为10元,

假设第一个人抢了10元,那么第二个人可以抢到的金额为(0 , (90/9)* 2)即(0 , 20)元,平均值为10元,以此类推。

// 发红包算法,金额参数以分为单位
	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++) {

			// 随机范围:[1,剩余人均金额的两倍),左闭右开

			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);
		}
	}

这里存在一个问题是第一个抢的人,最多只能获得人均金额的2倍,而如果前面抢到的红包越小,后面抢红包的人就越能抢到更大的红包,这里可以先随机出每份红包,放进list,然后将list随机排列

Collections.shuffle(amountList);
这样第一个抢红包的人也有可能多余获得人均金额的2倍的红包。

猜你喜欢

转载自blog.csdn.net/Rover__/article/details/80082624
今日推荐