Lua實戰之洗牌算法

Description

打亂指定table中的元素!

Implemention

-- 設置隨機數種子
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6)))

-- 洗牌算法
function shuffle(targetTbl)
    local tblLen = #targetTbl
    while(tblLen > 0)
    do
        local idx = math.random(tblLen)
        targetTbl[tblLen], targetTbl[idx] = targetTbl[idx], targetTbl[tblLen]
        tblLen = tblLen - 1
    end
    return targetTbl
end

-- test
local testTbl = {1, 2, 3, 4, 5, 6, 7, 8, 9}
local retTbl = shuffle(testTbl)
for k, v in pairs(retTbl) do
    print(k, v)    
end

--[[ 
1	4
2	6
3	2
4	1
5	9
6	8
7	5
8	3
9	7 
]]

ps:

Lua代碼在線測試網站:Execute Lua Online

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章