Last active
November 26, 2015 13:55
-
-
Save michalkot/8882fc7e28ae6ae3ba62 to your computer and use it in GitHub Desktop.
weightedRandom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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