RandomUtil_1.lua 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. RandomUtil = {}
  2. --根据权重随机词条数量
  3. function RandomUtil.random_weighted(weight_str, count)
  4. local result = {}
  5. if count <= 0 then
  6. return result
  7. end
  8. local num = string.split(weight_str, "|")
  9. local weight_total = 0
  10. for _, value in pairs(num) do
  11. local sum = string.split(value, "#")
  12. weight_total = weight_total + tonumber(sum[2])
  13. end
  14. local random_weight = math.random(1, weight_total)
  15. local cumulative_weight = 0
  16. for _, value in pairs(num) do
  17. local sum = string.split(value, "#")
  18. local weight = tonumber(sum[2])
  19. cumulative_weight = cumulative_weight + weight
  20. if cumulative_weight >= random_weight then
  21. table.insert(result, tonumber(sum[1]))
  22. if table.count(result) == count then
  23. return result
  24. end
  25. end
  26. end
  27. end
  28. -- 示例:"1#80|2#10|3#10"
  29. -- 80%的概率选中1
  30. -- 10%的概率选中2
  31. -- 80%的概率选中3
  32. function RandomUtil.selectKey(configStr)
  33. local results = RandomUtil.random_weighted(configStr, 1)
  34. local num = results[1]
  35. return num;
  36. end