Skip to content

Instantly share code, notes, and snippets.

@michalkot
Last active November 26, 2015 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalkot/8882fc7e28ae6ae3ba62 to your computer and use it in GitHub Desktop.
Save michalkot/8882fc7e28ae6ae3ba62 to your computer and use it in GitHub Desktop.
weightedRandom
function weightedRandom(ar) {
var ar = ar.sort(x => x.w);
var sum = ar.reduce((p, c) => p + c.w, 0);
// normalise
var soFar = 0;
ar.map(o => {
o.w = o.w / sum;
o.w += soFar;
soFar += o.w;
});
var item, r = Math.random();
while ((item = ar.shift()) && r > item.w);
return item && item.w;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment