Created
February 16, 2016 09:39
-
-
Save mogelbrod/f7963caeda6f85a0ef3f to your computer and use it in GitHub Desktop.
Weighted random choice in JavaScript, takes an array of non-negative weights
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 weightedChoice(weights) { | |
const weightSum = weights.reduce((sum, w) => sum + w) | |
let choice = Math.floor(Math.random() * weightSum) + 1 | |
let idx = weights.length - 1 | |
while ((choice -= weights[idx]) > 0) { | |
idx -= 1 | |
} | |
return idx | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment