用lua编写带权重的随机池
时间: 2023-07-15 19:12:20 浏览: 131
以下是一个简单的带权重的随机池的Lua实现:
```lua
function weighted_random_pool(items)
local pool = {}
local total_weight = 0
for item, weight in pairs(items) do
total_weight = total_weight + weight
pool[total_weight] = item
end
return function()
local rand_weight = math.random(total_weight)
for weight, item in pairs(pool) do
if rand_weight <= weight then
return item
end
end
end
end
```
使用示例:
```lua
local items = {
["apple"] = 1,
["banana"] = 2,
["orange"] = 3,
}
local random_item = weighted_random_pool(items)
for i = 1, 10 do
print(random_item())
end
```
输出结果类似于:
```
orange
orange
orange
banana
orange
banana
orange
orange
banana
orange
```
其中,每种水果的出现频率与其权重成正比。例如,橙子的权重是3,因此它在随机池中出现的概率是其他水果的三倍。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)