Asked 6 years ago
21 Feb 2018
Views 1496
pratik

pratik posted

Weighted Probability Problem in Javascript

Weighted Probability Problem in Javascript

Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00


var r=[{'name':'a','a':2},{'name':'d','a':1},{'name':'z','a':3},{'name':'l','a':0}];
 

sumOfWeights=lodash.sumBy(r, 'a');
 
randomWeight = lodash.random(1, sumOfWeights);
i=0;
while(randomWeight<=0){
value=r[i];
randomWeight = randomWeight - value.a;
 
i++;
  if (randomWeight<=0){
	console.log(value);
	break;
   }
}
Post Answer