实现一个分配随机红包的JS算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccaoee/article/details/82529520

前因

之前面试的时候,面试官出题让说出生成随机红包的算法的思路,事后,感觉可以仔细研讨下,遂有此文。

后果

条件

  1. 获取红包的份额不能超过一个阈值。
  2. 随机红包

思路

  1. 随机出最小值0到红包奖池有效值乘以阈值的值,这样确保每次获取的值都在有效范围内,这里的阈值是0.618
  2. 将随机后的值从红包奖池减去。确保红包奖池内都是有效值。
  3. 重复操作n - 1次。
  4. 将最后剩余的值直接推入结果数组中(在最后一次不需要进行阈值的检查)。

算法

//洗牌 //抽牌法优化牌
function shuffle_pick(arr) {
    //每次抽出一张牌,放在另一堆。把最后一张未抽的牌放在空位子上。
    const arr2 = []
    for (let len = arr.length;len>0;) {
        let rnd = Math.floor(Math.random() * len)
        arr2.push(arr[rnd])
        arr[rnd] = arr[--len]
    }
    return arr2
}

function randomRange(min, max) {
    return parseFloat((Math.random() * (max - min) + min).toFixed(2))
}
/**
 * 针对不同的阈值,随机红包函数的生成器
 * @param threshold = 0.618 阈值
 */
function randomRedPacketGenerator(threshold = 0.618) {
    if (threshold < 0 || threshold > 1) {
        throw new TypeError('range of threshold\'s value is wrong, it\'s value expect in range of [0, 1]')
    }
    return function(money, count) {
        let result = []
        for (let i=0;i<count - 1;i++) {
            const value = randomRange(0.01, money * threshold)
            result.push(value)
            money = money - value
        }
        result.push(parseFloat(money.toFixed(2)))
        console.log('before shuffle:', result)
        // 将结果数组洗牌
        result = shuffle_pick(result)
        return result
    }
}
// 示例:
// 得到随机红包函数
const randomRedPacket = randomRedPacketGenerator(0.6)
const arr = randomRedPacket(10, 10)
// log打印
const sum = arr.reduce((pre, cur) => {
    cur += pre
    return cur
}, 0)
console.log('arr:', arr)
console.log('sum:', parseFloat(sum.toFixed(10)))

参考链接

  1. 随机问题之–洗牌算法
  2. 数组的完全随机排列

猜你喜欢

转载自blog.csdn.net/ccaoee/article/details/82529520