碰到这样一个问题,觉得有点意思,随手把算法写出来:
多人随机抽奖,每个人的幸运值不一样,幸运值越大,概率越高,这样的抽奖算法怎么写?原贴如下:
https://developers.weixin.qq.com/community/develop/doc/000ac0127f058824e69b9d6f15b800
解决方案如下:
testLuckRandom: function () {
let luckers = [
{
openid: '1',
luckValue: 3,
},
{
openid: '2',
luckValue: 4,
},
{
openid: '3',
luckValue: 5,
},
{
openid: '4',
luckValue: 2,
},
{
openid: '5',
luckValue: 6,
},
{
openid: '6',
luckValue: 8,
},
]
//获得所有幸运值的和
let total = luckers.reduce((t, v) => {
v.scope = [t, t + v.luckValue] //设置该幸运儿的区间值
return t + v.luckValue
}, 0)
let ran = total * Math.random() //获得基于幸运值总和的随机值
let lucker = luckers.find(v => ran > v.scope[0] && ran <= v.scope[1]) //找到这个随机值落在哪个幸运儿的区间里。
console.log(total, ran, lucker)
},
至于luckers的构建,原问题里说到共有4000多个人参加抽奖,怎么一次从库里获取超过1000条记录呢?
有现成的方案,参考老张的贴子:
https://developers.weixin.qq.com/community/develop/article/doc/0008ea04120a18f6988b86d065b013
请问,luckValue: 0, 全部是0的话,为什么lucker为undefined?
666