RosettaCodeData/Task/Knuth-shuffle/Lua/knuth-shuffle.lua

14 lines
250 B
Lua
Raw Permalink Normal View History

2013-04-10 12:38:42 -07:00
function table.shuffle(t)
2016-12-05 22:15:40 +01:00
for n = #t, 1, -1 do
2013-04-10 12:38:42 -07:00
local k = math.random(n)
t[n], t[k] = t[k], t[n]
end
return t
end
2016-12-05 22:15:40 +01:00
2013-04-10 12:38:42 -07:00
math.randomseed( os.time() )
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
table.shuffle(a)
for i,v in ipairs(a) do print(i,v) end