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())
网友评论