Created
June 18, 2015 07:33
-
-
Save zlumer/95004de5f7062abfd36d to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Передаём веса в формате { potion:200, sword:15, unique_sword:1 } | |
*/ | |
function getRandom(weights) | |
{ | |
var total = calculateWeightsTotal(weights); // считаем суммарный вес | |
var rnd = Math.random() * total; // генерируем случайное число размером с максимальный вес | |
for (var s in weights) | |
{ | |
rnd -= weights[s]; | |
if (rnd <= 0) | |
return s; | |
} | |
return null; | |
} | |
function calculateWeightsTotal(weights) | |
{ | |
var sum = 0; | |
for (var s in weights) | |
{ | |
sum += weights[s]; | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment