function redP(nums, total) {
let packs = Array(nums);
let i = 0, random = 0;
while(i < nums) {
if(i === nums-1) {
random = total
} else {
random = ( Math.random() * total ).toFixed(2)
total = (total-random).toFixed(2)
}
packs[i] = random
i++
}
return packs
}
redP(6,100)
缺点:抢红包的先后顺序出现不公平,先抢的红包金额多
二倍均值法
function redP(nums, total) {
let packs = Array(nums)
let i = 0,random= 0,temp=0;
while(i < nums) {
if(i === nums-1) {
random = total
} else {
//temp = ((Math.random() * total)/(nums-i)*2)
temp = Math.random() * (total/(nums-i)*2)
random = temp.toFixed(2)
}
packs[i] = random;
i++
total = (total - random).toFixed(2)
}
return packs
}
redP(6,100)
保证红包最少抢到6,最多抢到20
function redP(nums, total) {
let packs = Array(nums)
let i = 0,random= 0,temp=0;
while(i < nums) {
if(i === nums-1) {
random = total
} else {
temp = ((Math.random() * total)/(nums-i)*2)+6
if(temp > 20) {
temp = 20
}
random = temp.toFixed(2)
}
packs[i] = random;
i++
total = (total - random).toFixed(2)
}
return packs
}
redP(6,100)
初始版
缺点:抢红包的先后顺序出现不公平,先抢的红包金额多
二倍均值法
保证红包最少抢到6,最多抢到20