带权重随机算法

放肆的年华 提交于 2020-01-09 19:04:59

闲言碎语不要讲,咱们直接上代码:

有什么讲的不对的地方,希望大家不吝赐教,感谢😊😊😊

let data = [{
    weight: 20,
    content: 'a'
}, {
    weight: 40,
    content: 'b'
}, {
    weight: 30,
    content: 'c'
}, {
    weight: 10,
    content: 'd'
}];

/** 总权重法 */
function getRandom() {
    let sum = 0;
    for (let i = 0; i < data.length; i++) {
        sum += data[i].weight;
    }
    let random = Math.floor(Math.random() * sum);
    console.log(random);
    sum = 0;
    for (let i = 0; i < data.length; i++) {
        let weight = data[i].weight + sum;
        if (random >= sum && random < weight) {
            console.log(data[i]);
            return data[i];
        }
        sum = weight;
    }
}

/** 先写的有大权重,后写得分剩下的权重 */
function getRandom1() {
    let random = Math.floor(Math.random() * 100);
    console.log('random', random);
    for (let i = 0; i < data.length; i++) {
        if (random <= data[i].weight) {
            return data[i];
        } else {
            random = Math.floor(Math.random() * 100);
        }
    }
    return data[data.length - 1];
}


function getRandom2() {
    let newData = [];
    for (let i = 0; i < data.length; i++) {
        let item = data[i];
        for (let j = 0; j < item.weight; j++) {
            newData.push(item);
        }
    }
    let randomIndex = Math.floor(Math.random() * newData.length);
    console.log(newData.length, randomIndex, newData[randomIndex]);
    return newData[randomIndex];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!