I have a table like follows:
Potion { id, name, freq }
I gave away potions to users in ‘random’ manner. but I want to be able to control frequency of the randomness because some potions is more powerful than others. What’s the best way to do this?
I am thinking of something like this:
id | name | freq
-------------------
1 | light | 5
2 | fire | 10
3 | water | 10
4 | earth | 10
5 | air | 5
light and air are more powerful than fire, water, and earth so they have smaller frequencies.
sum = select sum(*) from potions;
x = random(1..sum)
table = select * from potions;
offset = 0
for each element in table
if offset + element[freq] > x
chosen = element[name]
end
offset += element[freq]
end
I think the code above (ruby + sql) will works but its not scalable and i very much doubt it that it’s the most efficient way of doing it. Could anyone please help me to do so?
Thank you in advance,
You first need to create a view on top of
RAND()so it returns the same value for each invocation during execution (otherwise you’ll get weird results):Next select a random row weighted by the cumulative freq: