美文网首页
房卡棋牌,生成唯一的房间ID,算法

房卡棋牌,生成唯一的房间ID,算法

作者: 漂泊的树叶hx | 来源:发表于2019-03-14 20:25 被阅读0次

用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

相关文章

网友评论

      本文标题:房卡棋牌,生成唯一的房间ID,算法

      本文链接:https://www.haomeiwen.com/subject/jlchmqtx.html