ch06 exercises
This commit is contained in:
34
exercises/ch06/ex6_4.lua
Normal file
34
exercises/ch06/ex6_4.lua
Normal file
@@ -0,0 +1,34 @@
|
||||
local function shuffle(l)
|
||||
for i = 1, #l do
|
||||
local new_i = math.random(1, #l)
|
||||
local tmp = l[new_i]
|
||||
l[new_i] = l[i]
|
||||
l[i] = tmp
|
||||
end
|
||||
end
|
||||
|
||||
local function table_str(t)
|
||||
local str = "{"
|
||||
for _, v in pairs(t) do
|
||||
if type(v) == "string" then
|
||||
v = '"' .. v .. '"'
|
||||
end
|
||||
str = ("%s %s,"):format(str, v)
|
||||
end
|
||||
|
||||
str = str .. " }"
|
||||
|
||||
return str
|
||||
end
|
||||
|
||||
local function test(l)
|
||||
local str = ("%s -> "):format(table_str(l))
|
||||
shuffle(l)
|
||||
str = str .. table_str(l)
|
||||
print(str)
|
||||
end
|
||||
|
||||
math.randomseed(os.time())
|
||||
|
||||
test({ 1, 2, 3, 4 })
|
||||
test({ "a", "b", "c", "d" })
|
||||
Reference in New Issue
Block a user