function cAve(money, num) {
let arr = []
function c() {
for (let i = 0; i < num; i++) {
if (!arr[i]) {
arr[i] = 0
}
if (money > 0) {
arr[i] += 0.01
money -= 0.01
}
}
if (money <= 0) {
return
}
c()
}
c()
console.log(arr)
return arr
}
/**
* 红包分配
* @param {Number} money -金额/元
* @param {Number} num -人数
* @return {Array} 金额数组
*/
function redPackage(money = 0.01, num = 1) {
if (money / num < 0.01) {
console.log('超过分配限额')
return
}
let moneyArr = cAve(money, num)
let mdArr = []
// 平均数
const ave = money / num
for (let i = 0; i < num; i++) {
let ave = moneyArr[i]
if (ave === 0.01) {
moneyArr[i] = ave
mdArr.push(0)
return
}
let md = Number((new Big(Number(Math.random().toFixed(2)))).times(ave).toString())
if (md < 0.01) {
md = 0.01
}
console.log(md)
mdArr.push(md)
let x = new Big(ave)
moneyArr[i] = Number(x.minus(md).toString())
}
// 打乱顺序
mdArr.reverse()
// 相加
moneyArr = moneyArr.map((item, index) => {
item + mdArr[index]
let x = new Big(item)
return Number(x.plus(mdArr[index]).toString())
})
// 保证最大值唯一
console.log(moneyArr)
console.log(moneyArr.reduce((a, b) => {
return Number((new Big(a)).plus(b).toString())
}))
return []
}
redPackage(1, 90)
redPackage(10, 5)
redPackage(1, 10)
console