二倍均值法
公式: 每次抢到金额 = 随机区间(0, M/N*2);【M:剩余金额,N:剩余红包个数】
// 条件:最少1分钱”
function divide(totalMoney, totalCount) {
// totalMoney:总金额
// totolCount:总份数
let leftMoney = totalMoney,
leftCount = totalCount;
let arr = [];
// 随机发n-1个红包,最后一个红包不需要随机
for (var i = 0; i < totalCount - 1; i++) {
// 按照公式生成随机金额
let money = parseFloat(Math.random()*(leftMoney / leftCount * 2) + 0.01).toFixed(2);
// 将随机红包存入
arr.push(money);
leftMoney -= money;
leftCount--;
}
// 最后一个红包不需要随机
arr.push(parseFloat(leftMoney).toFixed(2));
console.log(arr);
}
divide(10, 5);