@@ -3,6 +3,7 @@ local pairs = pairs
33local next = next
44local tonumber = tonumber
55local setmetatable = setmetatable
6+ local math_random = math.random
67
78
89local _M = {}
@@ -46,18 +47,35 @@ local function get_gcd(nodes)
4647 return only_key , gcd , max_weight
4748end
4849
50+ local function get_random_node_id (nodes )
51+ local count = 0
52+ for _ , _ in pairs (nodes ) do
53+ count = count + 1
54+ end
55+
56+ local id = nil
57+ local random_index = math_random (count )
58+
59+ for _ = 1 , random_index do
60+ id = next (nodes , id )
61+ end
62+
63+ return id
64+ end
65+
4966
5067function _M .new (_ , nodes )
5168 local newnodes = copy (nodes )
5269 local only_key , gcd , max_weight = get_gcd (newnodes )
70+ local last_id = get_random_node_id (nodes )
5371
5472 local self = {
5573 nodes = newnodes , -- it's safer to copy one
5674 only_key = only_key ,
5775 max_weight = max_weight ,
5876 gcd = gcd ,
5977 cw = max_weight ,
60- last_id = nil ,
78+ last_id = last_id ,
6179 }
6280 return setmetatable (self , mt )
6381end
@@ -68,7 +86,7 @@ function _M.reinit(self, nodes)
6886 self .only_key , self .gcd , self .max_weight = get_gcd (newnodes )
6987
7088 self .nodes = newnodes
71- self .last_id = nil
89+ self .last_id = get_random_node_id ( nodes )
7290 self .cw = self .max_weight
7391end
7492
0 commit comments