Skip to content

Instantly share code, notes, and snippets.

@rendfall
Created November 14, 2017 23:44
Show Gist options
  • Save rendfall/4045581ff187b2ed9d1a600ed6de4260 to your computer and use it in GitHub Desktop.
Save rendfall/4045581ff187b2ed9d1a600ed6de4260 to your computer and use it in GitHub Desktop.
Generate a weighted random number
// Source: https://stackoverflow.com/a/8435261
function weightedRand(spec) {
let i, j, table = [];
for (i in spec) {
// The constant 10 below should be computed based on the
// weights in the spec for a correct and optimal table size.
// E.g. the spec {0:0.999, 1:0.001} will break this impl.
for (j = 0; j < spec[i] * 10; j++) {
table.push(i);
}
}
return function() {
return table[Math.floor(Math.random() * table.length)];
}
}
// weightedRand({
// 0: 0.8,
// 1: 0.1,
// 2: 0.1
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment