Created
April 26, 2017 09:19
-
-
Save Aleksey-Danchin/5b3b0ceed45021031bcff1a755377be6 to your computer and use it in GitHub Desktop.
Генератор рандомера по фиксированному множеству вероятностей.
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
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