微信分享常用活动方案-砍价【随机算法】

it2025-01-13  5

//判断创建的方案是否正确 function verifyScheme(money,count,max,min) { //判断最小砍价金额是否大于最大砍价金额 if(min > max){ return '设置的最小砍价金额不能大于最大砍价金额' } //判断当前的最大金额乘以次数是否小于总砍价 if(count * max < money){ return `设置的最大金额最少为:${money / count}` } //判断当前的最小金额设置是否大于总砍价金额 if(count * min > money){ return `设置的最小金额最多为:${money / count}` } return 1; } //每次一输入最小砍价金额,计算最大金额的区间 function cutPrice(min,count,price){ return [price / count,price - (min * (count - 1))]; } //创建一次砍价活动,前端计算。 function cutPrice(money,count,max,min = 0.01) { let verRes = verifyScheme(money,count,max,min) if(verRes != 1){ throw new Error(verRes) } let curPriceList = [],nowMax,nowMin,nowPrice; //所有数全部乘以100; money *= 100; max *= 100; min *= 100; for(let i = 0 ; i < count;i++) { //最大刀数 nowMax = money-(count- i - 1) * min; if(nowMax > max){ nowMax = max; } //最小刀数 nowMin = money - max * (count - i - 1); nowMin = min < nowMin ? nowMin : min; //得到当前的价格 nowPrice = MathRondom(nowMax,nowMin); curPriceList.push(nowPrice); money -= nowPrice; console.log(`最大为:${nowMax/100},最小为${nowMin/100},【砍掉金额${nowPrice/100}】,剩余金额:${money/100},当前刀数${i+1},剩余刀数:${count-i-1}`) } return curPriceList.map(item=>item/100); } //创造随机区间 function MathRondom(max,min) { return min + Math.floor(Math.random() * (max - min + 1)); } //测试 let cutPriceList = cutPrice(99,10,20,5); let count = 0; cutPriceList.forEach(item=>{ count += (item*100) }) console.log(count/100)

最新回复(0)