南锋

南奔万里空,脱死锋镝余

Lua 随机打乱数组:Fisher-Yates 洗牌算法与复制版本

使用 Fisher-Yates 原地打乱数组

1
2
3
4
5
6
7
local function shuffle(items)
for i = #items, 2, -1 do
local j = math.random(i)
items[i], items[j] = items[j], items[i]
end
return items
end

该算法从数组末尾开始,每次与当前位置之前的随机元素交换,时间复杂度为 O(n)。如需保留原始顺序,应先复制数组再调用 shuffle