1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
| -- 圆桌随机类
g_tRoundTable = {}
g_tRoundTable.__index = g_tRoundTable
-- 构造函数
-- mergeSameKey: 相同id+weight的项会合并成一个节点,用count记录数量(默认 true)
-- useIndex: 使用哈希表加速查找,空间换时间
-- indexDirty: 延迟重建索引,批量操作优化
function g_tRoundTable:new(opts)
opts = opts or {}
local instance = {
items = {}, -- 存储随机项:{id, weight, count, totalWeight}
prefixSums = {}, -- 累计权重前缀和数组,用于二分查找
indexMap = {}, -- key->index 的哈希表,快速定位
totalWeight = 0, -- 总权重
totalCount = 0, -- 总数量
lastError = "", -- 最后的错误信息
mergeSameKey = opts.mergeSameKey ~= false, -- 是否合并相同项(默认true)
useIndex = opts.useIndex, -- 是否使用索引,未指定则根据mergeSameKey决定
indexDirty = false, -- 索引是否需要重建
}
-- 默认:mergeSameKey=true 时才使用索引
if instance.useIndex == nil then
instance.useIndex = instance.mergeSameKey
end
setmetatable(instance, self)
return instance
end
-- 生成唯一索引键:"id|weight"
function g_tRoundTable:_buildKey(id, weight)
return tostring(id) .. "|" .. tostring(weight)
end
-- 增量更新前缀和(从startIndex开始全部加delta)
function g_tRoundTable:_applyDelta(startIndex, delta)
for i = startIndex, #self.prefixSums do
self.prefixSums[i] = self.prefixSums[i] + delta
end
end
-- 增量式索引更新:移除指定位置的索引并调整后续索引
function g_tRoundTable:_removeIndexAt(index)
if not self.useIndex then
return
end
local node = self.items[index]
if node then
local key = self:_buildKey(node.id, node.weight)
self.indexMap[key] = nil -- 删除该位置索引
end
-- 后续索引位置前移
for key, idx in pairs(self.indexMap) do
if idx > index then
self.indexMap[key] = idx - 1
end
end
end
-- 重建索引表(仅在必要时调用)
function g_tRoundTable:_rebuildIndex()
if not self.useIndex then
return
end
self.indexMap = {}
for idx, node in ipairs(self.items) do
local key = self:_buildKey(node.id, node.weight)
self.indexMap[key] = idx
end
self.indexDirty = false
end
-- 确保索引是最新的
function g_tRoundTable:_ensureIndexFresh()
if self.indexDirty then
self:_rebuildIndex()
end
end
-- 清空所有随机项
function g_tRoundTable:clearItems()
self.items = {}
self.prefixSums = {}
self.indexMap = {}
self.totalWeight = 0
self.totalCount = 0
self.lastError = ""
self.indexDirty = false
end
-- 添加随机项
-- count:同权重、同ID的重复次数(默认 1)
function g_tRoundTable:addItem(id, weight, count)
if type(weight) ~= "number" or weight <= 0 then
self.lastError = "Invalid weight: " .. tostring(weight)
return false
end
count = count or 1
if count < 1 then
self.lastError = "Invalid count: " .. tostring(count)
return false
end
local weightDelta = weight * count
-- 是否合并相同项
if self.mergeSameKey then
self:_ensureIndexFresh() -- 确保索引最新
local key = self:_buildKey(id, weight)
local idx = self.useIndex and self.indexMap[key] or nil
if idx then
-- 已经存在,则累加count和totalWeight
local node = self.items[idx]
node.count = node.count + count
node.totalWeight = node.totalWeight + weightDelta
self:_applyDelta(idx, weightDelta) -- 增量更新前缀和
else
-- 新增节点
local node = {id = id, weight = weight, count = count, totalWeight = weightDelta}
table.insert(self.items, node)
local prev = self.prefixSums[#self.prefixSums] or 0
table.insert(self.prefixSums, prev + weightDelta)
if self.useIndex then
self.indexMap[key] = #self.items
end
end
else -- 不合并,则直接添加
local node = {id = id, weight = weight, count = count, totalWeight = weightDelta}
table.insert(self.items, node)
local prev = self.prefixSums[#self.prefixSums] or 0
table.insert(self.prefixSums, prev + weightDelta)
end
self.totalWeight = self.totalWeight + weightDelta
self.totalCount = self.totalCount + count
return true
end
-- 获取随机数
-- 不传参时返回 [0,1) 的浮点数;传参时调用 math.random(low, high)
function g_tRoundTable:getRandom(low, high)
if low and high then
return math.random(low, high)
end
return math.random()
end
-- 检查池子状态
function g_tRoundTable:_ensureReady()
if self.totalWeight <= 0 or #self.items == 0 then
self.lastError = "No items to fetch from"
return false
end
return true
end
-- 二分查找定位随机区间
function g_tRoundTable:_binarySearch(value)
local low, high = 1, #self.prefixSums
while low < high do
local mid = math.floor((low + high) / 2)
-- 改进:使用 < 而非 <=,更准确
if value < self.prefixSums[mid] then
high = mid
else
low = mid + 1
end
end
return low
end
-- 消费一个节点(非独立模式用)
function g_tRoundTable:_consume(index)
local node = self.items[index]
local delta = node.weight
node.count = node.count - 1
node.totalWeight = node.totalWeight - delta
self.totalWeight = self.totalWeight - delta
self.totalCount = self.totalCount - 1
self:_applyDelta(index, -delta) -- 减少权重
if node.count <= 0 then
-- 节点用完,移除(增量式索引更新,只调整受影响的索引,避免完整重建)
self:_removeIndexAt(index)
table.remove(self.items, index)
table.remove(self.prefixSums, index)
end
end
-- 批量设置随机项,支持输入重复数据
-- rawItems 示例:{ {id=1, weight=10}, {id=1, weight=10}, {id=2, weight=20} }
function g_tRoundTable:setItems(rawItems)
self:clearItems()
if type(rawItems) ~= "table" then
self.lastError = "Items must be a table"
return false
end
for _, item in ipairs(rawItems) do
if not self:addItem(item.id, item.weight, item.count or 1) then
return false
end
end
return true
end
-- 提取随机项
-- count:抽取数量
-- independent:true 为独立抽取(放回),false 为非独立抽取(不放回)
function g_tRoundTable:fetchItems(count, independent)
count = count or 1
if count < 1 then
self.lastError = "Fetch count must be positive"
return {}
end
-- 非独立模式下检查数量是否足够
if not independent and count > self.totalCount then
self.lastError = string.format("Insufficient items: need %d, have %d", count, self.totalCount)
return {}
end
local results = {}
for _ = 1, count do
if not self:_ensureReady() then
break
end
-- 生成 [0, totalWeight) 的随机数
local randomValue = self:getRandom() * self.totalWeight
if randomValue >= self.totalWeight then
randomValue = self.totalWeight - 0.0001 -- 确保不会超出边界
end
if randomValue <= 0 then
randomValue = self.totalWeight
end
-- 二分查找定位
local idx = self:_binarySearch(randomValue)
local node = self.items[idx]
table.insert(results, node.id)
-- 非独立抽取时消费该项
if not independent then
self:_consume(idx)
end
end
return results
end
-- 调整某个 id+weight 的数量,可正可负
function g_tRoundTable:modifyItemCount(id, weight, deltaCount)
if deltaCount == 0 then
return true
end
self:_ensureIndexFresh() -- 确保索引最新
local key = self.mergeSameKey and self:_buildKey(id, weight) or nil
local idx = (key and self.useIndex) and self.indexMap[key] or nil
if not idx then
if deltaCount < 0 then
self.lastError = string.format("Item(%s,%s) not found", tostring(id), tostring(weight))
return false
end
-- 不存在则新增,直接 addItem
return self:addItem(id, weight, deltaCount)
end
local node = self.items[idx]
local newCount = node.count + deltaCount
if newCount < 0 then
self.lastError = string.format("Modify would make count negative: id=%s weight=%s", tostring(id), tostring(weight))
return false
end
local deltaWeight = node.weight * deltaCount
node.count = newCount
node.totalWeight = node.totalWeight + deltaWeight
self.totalWeight = self.totalWeight + deltaWeight
self.totalCount = self.totalCount + deltaCount
self:_applyDelta(idx, deltaWeight)
if node.count == 0 then
-- 增量式索引更新,只调整受影响的索引,避免完整重建
self:_removeIndexAt(idx)
table.remove(self.items, idx)
table.remove(self.prefixSums, idx)
end
return true
end
-- 删除指定 id+weight(整条移除,不管 count)
function g_tRoundTable:removeItem(id, weight)
self:_ensureIndexFresh() -- 确保索引最新
local key = self.mergeSameKey and self:_buildKey(id, weight) or nil
local idx = (key and self.useIndex) and self.indexMap[key] or nil
if not idx then
self.lastError = string.format("Item(%s,%s) not found", tostring(id), tostring(weight))
return false
end
local node = self.items[idx]
self.totalWeight = self.totalWeight - node.totalWeight
self.totalCount = self.totalCount - node.count
-- 增量式索引更新,只调整受影响的索引,避免完整重建
self:_removeIndexAt(idx)
table.remove(self.items, idx)
table.remove(self.prefixSums, idx)
return true
end
-- 替换 / 设置某个 id 的权重(保留 count)
function g_tRoundTable:setItemWeight(id, oldWeight, newWeight)
if newWeight <= 0 then
self.lastError = "Invalid new weight: " .. tostring(newWeight)
return false
end
self:_ensureIndexFresh() -- 确保索引最新
local key = self.mergeSameKey and self:_buildKey(id, oldWeight) or nil
local idx = (key and self.useIndex) and self.indexMap[key] or nil
if not idx then
self.lastError = string.format("Item(%s,%s) not found", tostring(id), tostring(oldWeight))
return false
end
local node = self.items[idx]
local deltaWeight = (newWeight - node.weight) * node.count
node.weight = newWeight
node.totalWeight = newWeight * node.count
self.totalWeight = self.totalWeight + deltaWeight
self:_applyDelta(idx, deltaWeight)
if self.mergeSameKey then
self.indexMap[key] = nil
local newKey = self:_buildKey(id, newWeight)
self.indexMap[newKey] = idx
end
return true
end
-- 批量操作接口
-- operations 格式:
-- {
-- {action = "add", id = 1, weight = 10, count = 5},
-- {action = "modify", id = 2, weight = 20, deltaCount = 3},
-- {action = "remove", id = 3, weight = 15},
-- {action = "setWeight", id = 4, oldWeight = 10, newWeight = 15}
-- }
function g_tRoundTable:batchModify(operations)
if type(operations) ~= "table" then
self.lastError = "Operations must be a table"
return false
end
local needRebuild = false -- 批量操作期间标记索引为脏,延迟重建
for _, op in ipairs(operations) do
local success = false
if op.action == "add" then
success = self:addItem(op.id, op.weight, op.count or 1)
elseif op.action == "modify" then
success = self:modifyItemCount(op.id, op.weight, op.deltaCount or 0)
needRebuild = true
elseif op.action == "remove" then
success = self:removeItem(op.id, op.weight)
needRebuild = true
elseif op.action == "setWeight" then
success = self:setItemWeight(op.id, op.oldWeight, op.newWeight)
else
self.lastError = "Unknown action: " .. tostring(op.action)
return false
end
if not success then
return false
end
end
-- 批量操作完成后统一重建索引
if needRebuild then
self:_rebuildIndex()
end
return true
end
-- 获取当前池子(expand=true 时会展开成原始形式)
function g_tRoundTable:getAllItems(expand)
if expand then
local flat = {}
for _, node in ipairs(self.items) do
for _ = 1, node.count do
table.insert(flat, {id = node.id, weight = node.weight})
end
end
return flat
end
local snapshot = {}
for _, node in ipairs(self.items) do
table.insert(snapshot, {
id = node.id,
weight = node.weight,
count = node.count,
totalWeight = node.totalWeight
})
end
return snapshot
end
-- 标记索引为脏,延迟重建
function g_tRoundTable:_markIndexDirty()
if self.useIndex then
self.indexDirty = true
end
end
-- 获取内存使用情况
function g_tRoundTable:getMemoryInfo()
local itemsMemory = #self.items * 4 -- 粗略估算(每个节点4个字段)
local prefixSumsMemory = #self.prefixSums
local indexMemory = 0
if self.useIndex then
for _ in pairs(self.indexMap) do
indexMemory = indexMemory + 1
end
end
return {
itemCount = #self.items,
prefixSumCount = #self.prefixSums,
indexCount = indexMemory,
useIndex = self.useIndex,
mergeSameKey = self.mergeSameKey,
estimatedNodes = itemsMemory + prefixSumsMemory + indexMemory
}
end
-- 动态切换索引模式(仅在mergeSameKey=true时有效)
function g_tRoundTable:setUseIndex(enabled)
if not self.mergeSameKey then
self.lastError = "Index can only be used when mergeSameKey is true"
return false
end
if enabled == self.useIndex then
return true
end
self.useIndex = enabled
if enabled then
-- 启用索引,重建
self:_rebuildIndex()
else
-- 禁用索引,释放内存
self.indexMap = {}
self.indexDirty = false
end
return true
end
-- 获取最近一次错误
function g_tRoundTable:getLastError()
return self.lastError
end
|