Skip to content

Instantly share code, notes, and snippets.

@mogelbrod
Created February 16, 2016 09:39
Show Gist options
  • Save mogelbrod/f7963caeda6f85a0ef3f to your computer and use it in GitHub Desktop.
Save mogelbrod/f7963caeda6f85a0ef3f to your computer and use it in GitHub Desktop.
Weighted random choice in JavaScript, takes an array of non-negative weights
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