如何加上"权重和QUOT;到MySQL表,并根据这些选择随机值? [英] How to add "weights" to a MySQL table and select random values according to these?
问题描述
我想创建一个表,其中包含某种权重中的每一行。然后,我要选择的概率等于(重量该行)/(重量全部行)随机值。例如,具有5列权重1,2,3,4,5出1000我会得到大约为1/15 * 1000 = 67次第一排等。
I want to create a table, with each row containing some sort of weight. Then I want to select random values with the probability equal to (weight of that row)/(weight of all rows). For example, having 5 rows with weights 1,2,3,4,5 out of 1000 I'd get approximately 1/15*1000=67 times first row and so on.
的表是手动填充。然后,我将采取从它的随机值。但我想有一个改变在灌浆期的概率能力。
The table is to be filled manually. Then I'll take a random value from it. But I want to have an ability to change the probabilities on the filling stage.
推荐答案
我发现这个的可爱的小算法在狴利贝特。你也许可以将其转换成一些程序上的SQL。
I found this nice little algorithm in Quod Libet. You could probably translate it to some procedural SQL.
function WeightedShuffle(list of items with weights):
max_score ← the sum of every item’s weight
choice ← random number in the range [0, max_score)
current ← 0
for each item (i, weight) in items:
current ← current + weight
if current ≥ choice or i is the last item:
return item i
这篇关于如何加上"权重和QUOT;到MySQL表,并根据这些选择随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!