權重隨機(Lua)

2021-09-05 11:05:12 字數 2074 閱讀 7172

使用語言:lua

實現權重隨機步驟:

--[[

function:權重隨機函式

param1:要隨機的表

param2:權重列表

return:返回的隨機值

]]function getranombyweight(t, weights)

local sum = 0

for i = 1, #weights do

sum = sum + weights[i]

endlocal compareweight = math.random(1, sum)

local weightindex = 1

while sum > 0 do

sum = sum - weights[weightindex]

if sum < compareweight then

return t[weightindex]

endweightindex = weightindex + 1

endprint("compare error, return nil")

return nil

end--------------- test --------------

local weights =

local items =

local result =

local allrandomcount = 10000000

for i = 1, allrandomcount do

local randomvalue = getranombyweight(items, weights)

result[randomvalue] = result[randomvalue] + 1

endfor i = 1, #items do

local key = items[i]

local count = result[key]

local probability = count / allrandomcount

local resultstr = key .. ": " .. "count is " .. count .. " ,probability is " .. probability

print(resultstr)

end---------- allrandomcount = 100 ----------

a: count is 14 ,probability is 0.14

b: count is 14 ,probability is 0.14

c: count is 19 ,probability is 0.19

d: count is 19 ,probability is 0.19

e: count is 34 ,probability is 0.34

---------- allrandomcount = 10000 ----------

a: count is 1020 ,probability is 0.102

b: count is 1011 ,probability is 0.1011

c: count is 2049 ,probability is 0.2049

d: count is 1977 ,probability is 0.1977

e: count is 3943 ,probability is 0.3943

---------- allrandomcount = 10000000 ----------

a: count is 1001325 ,probability is 0.1001325

b: count is 1000326 ,probability is 0.1000326

c: count is 1999609 ,probability is 0.1999609

d: count is 1998877 ,probability is 0.1998877

e: count is 3999863 ,probability is 0.3999863

從測試資料來看,隨機次數越多,越接近單個權重值佔總權重值的比例

其他

按權重隨機

以下 為c 語言,變為其他語言也很容易。說明 1.該演算法複雜度為線性,且無需對權重排序。是我想到的最高效的了。private static list weightkey new list private static list weightvaluefloat new list private s...

權重隨機演算法

主要用於計算 ip池設計,實現概率選擇優質 ip,所以簡單寫了個權重隨機演算法。如果量大注意int 超限,預設20次 支援107374182個ip。權重物件類 public class ipweight public void setaddress string address public int...

演算法 權重隨機

權重物件 public class randomobject id public int id 四類寶箱中物品數量的權重 json格式資料 1,101 2,102 31,103 41,104 寶箱中具體物品數量的權重 json格式資料 1202,100 1203,100 1201,100 1210,...