Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Created April 26, 2017 09:19
Show Gist options
  • Save Aleksey-Danchin/5b3b0ceed45021031bcff1a755377be6 to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/5b3b0ceed45021031bcff1a755377be6 to your computer and use it in GitHub Desktop.
Генератор рандомера по фиксированному множеству вероятностей.
function getRandomer(...chances) {
const commonLength = chances.reduce((p, c) => p + c, 0)
, chancesLength = chances.length;
return function() {
const rIndex = Math.floor(Math.random() * commonLength);
let startIndex = - 0.5, lastIndex;
for (let i = 0; i < chancesLength; i++) {
lastIndex = startIndex + chances[i];
if (startIndex <= rIndex && rIndex <= lastIndex) {
return i;
}
startIndex = lastIndex;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment