美文网首页
根据不同的权重,随机取不同的内容

根据不同的权重,随机取不同的内容

作者: 不决书 | 来源:发表于2019-10-14 20:54 被阅读0次
var randInt = function(min,max) {
var ret = Number((Math.floor(Math.random()*(max-min+1)))+min);
return ret;
}
var random = exports.random = function(weights, keys){
var n = weights.length,
sumw = 0,
inx = [],
prob = [],
sht = [],
lng = [];
weights.forEach(function(weight, i){
sumw += weight;
inx.push(-1);
});
//console.log("sumw", sumw)
weights.forEach(function(weight, i){
prob.push(weight * n / sumw);
});
prob.forEach(function(p, i){
if(p < 1) sht.push(i);
if(p > 1) lng.push(i);
});
//console.log("sht", sht);
//console.log("lng", lng);
while(sht.length > 0 && lng.length > 0){
var j = sht.pop();
var k = lng[lng.length-1];
//assert.ok(prob[j] <= 1 <= prob[k], "Error with probability split.");
inx[j] = k;
prob[k] -= (1-prob[j]);
if(prob[k] < 1){
sht.push(k);
lng.pop();
}
}
//console.log("inx", inx);
return {
random : function(){
var u = Math.random(),
j = randInt(0, n-1), i;
//console.log("u", u);
//console.log("j", j);
i = (prob[j] >= u) ? j : inx[j];
//console.log(i)
return keys[i];
}
}
}
//调用方式:
var walker = require("../src/walker");
    
    //provide an array of weights
    var weights = [105, 181, 283, 431];
    
    //provide an array of keys that correlates to the weights
    var keys = ["A", "B", "C", "D"];
    
    //pass them into the constructor
    var wr = walker.random(weights, keys);
    
    // prints out A,B,C,D randomly based on the weighting
    console.log(wr.random())

相关文章

网友评论

      本文标题:根据不同的权重,随机取不同的内容

      本文链接:https://www.haomeiwen.com/subject/qissuctx.html