Skip to main content

分红包

切西瓜(总是切队列中最大的)

function distribute(money, count) {
money *= 100;
let res = [money];
while (--count) {
let maxMoney = -1,
maxIndex = 0;
// 维护一个队列,不断得到最大值
for (let i = 0; i < res.length; i++) {
if (res[i] > maxMoney) {
maxMoney = res[i];
maxIndex = i;
}
}
// 在最大值中不断去切,保证最少切出1块钱
let ran = Math.max(Math.floor(maxMoney * Math.random()), 1);
// 替换成,切出来的两部分****
// splice支持多参数
res.splice(maxIndex, 1, ran, maxMoney - ran);
}

// 后续需要除100
return res;
}

隔板法

function distribute(money, count) {
// 精确到小数点后两位
money *= 100;
let arr = new Array(money).fill(0).map((_, i) => i);
while (--count) {
// 插count次隔板,把隔板正好选到的数,移到第count个
let ran = Math.floor((money - 2) * Math.random()) + 1;
let temp = arr[count];
arr[count] = arr[ran];
arr[ran] = temp;
}
// 前十个数是十个count板子(不包括第0个,因为循环没走到)
let res = arr.slice(1, 10);
res.sort((a, b) => a - b);
// 最后一位总钱数
res.push(money);
// 算出各位的差
for (let i = res.length - 1; i > 0; i--) {
res[i] = res[i] - res[i - 1];
}
return res;
}