用lua实现取六位房间号ID算法
核心思想是保证生成出来的ID与现有ID不重复
从开始写此文章,到写完,算法还在执行 总共执行 999999 次。
所以此算法的弊端是,房间号生成的越多,越慢。
于是,把999999 改为 9999 总用时 1s,并没有细算到ms,如果ms应该在1s内
1s也可接受,毕竟要同时达到一万房间存在的话,地方棋牌也不容易!
99999 花费时间为 161s
RoomManager.lua
local idMgr = require('id_mgr')
function CMD.PlayerCreateRoom(roomData)
local startTime = os.time()
for i = 1,999999 do
idMgr:gen_id()
end
local endTime = os.time()
local totalTime = endTime - startTime
print('totalTime:"..totalTime)
print("id len:"..idMgr:getTblLen)
end
id_mgr.lua
function id_mgr:init()
self.tbl = {}
end
function id_mgr:gen_id()
if self.id_mgr == nil then
slef:init()
end
local bExit = true
local result = 0
while(bExit) do
result = math.random(1,999999) % 9999 + (math.random(1,999999) % 88 + 10) * 10000
bExit = self:isExist(result)
if result = 0 then
bExit = true
end
end
table.insert(self.tbl,result)
end
funtion id_mgr:isExist(id)
for i = 1, #self.tbl, 1 do
if self.tbl[i] == id then
return true
end
end
return false
end
网友评论