Created
November 14, 2017 23:44
-
-
Save rendfall/4045581ff187b2ed9d1a600ed6de4260 to your computer and use it in GitHub Desktop.
Generate a weighted random number
This file contains hidden or 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
// 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