I need to create a kind of roulette where a random prize comes out, taking into account:
- the type of prize, for example 5 different prizes better than others
- The better the lower the odds of getting out
- the stock of the prizes, take into account if the prize is still in stock
I was thinking of organizing values like this:
var premios = [
{ 'tipo': 'premio1', 'stock': 40, 'probabilidade': 0.5 },
{ 'tipo': 'premio2', 'stock': 40, 'probabilidade': 0.5 },
{ 'tipo': 'premio3', 'stock': 30, 'probabilidade': 0.4 },
{ 'tipo': 'premio4', 'stock': 10, 'probabilidade': 0.2 },
{ 'tipo': 'premio5', 'stock': 5, 'probabilidade': 0.1 }
];
I've been experimenting with several things, I think I got close to a solution but it's not working at 100%, the odds are not right. I'm a little lost, can anyone help?
function RandomProb () {
var s = 0,
pcnt = premios.length,
num = Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
for (var i = 0; i < pcnt; ++i) {
range = premios[i].probabilidade * 1000;
if (num < 1000-range && premios[i].stock) {
premios[i].stock--;
return premios[i].tipo;
}
}
};