使用lua写出带权重的随机池
时间: 2023-11-27 11:55:13 浏览: 48
以下是使用Lua实现带权重的随机池的代码:
```lua
function weightedRandom(choices)
local totalWeight = 0
for _, choice in ipairs(choices) do
totalWeight = totalWeight + choice.weight
end
local rand = math.random() * totalWeight
for _, choice in ipairs(choices) do
if rand < choice.weight then
return choice.value
end
rand = rand - choice.weight
end
end
```
这个函数接受一个包含选项和权重的表作为参数,其中每个选项都是一个带有`value`和`weight`属性的表。`value`是选项的值,`weight`是它的权重。
函数首先计算所有选项的总权重,然后使用`math.random()`生成一个0到1之间的随机数。随机数乘以总权重得到了一个0到总权重之间的随机数。然后,函数遍历每个选项,将该选项的权重从随机数中减去。如果随机数变为负数,则选择该选项。
以下是使用示例:
```lua
choices = {
{value = "A", weight = 2},
{value = "B", weight = 3},
{value = "C", weight = 5}
}
for i = 1, 10 do
print(weightedRandom(choices))
end
```
这个示例在每次调用`weightedRandom()`时,都会从给定的选项中随机选择一个,并输出选择的值。输出结果将根据每个选项的权重进行加权随机。