Skip to content

Instantly share code, notes, and snippets.

@zlumer
Created June 18, 2015 07:33
Show Gist options
  • Save zlumer/95004de5f7062abfd36d to your computer and use it in GitHub Desktop.
Save zlumer/95004de5f7062abfd36d to your computer and use it in GitHub Desktop.
/**
* Передаём веса в формате { 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