ch05 exercises
This commit is contained in:
39
exercises/ch05/ex5_7.lua
Normal file
39
exercises/ch05/ex5_7.lua
Normal file
@@ -0,0 +1,39 @@
|
||||
local function insert_into(insert, into, pos)
|
||||
local insert_i = 0
|
||||
for into_i = pos, #into + #insert do
|
||||
local new_into_i = into_i + #insert
|
||||
into[new_into_i] = into[into_i]
|
||||
into[into_i] = insert[insert_i]
|
||||
insert_i = insert_i + 1
|
||||
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(insert, into, pos)
|
||||
print("------------------------------")
|
||||
print(("pos: %d"):format(pos))
|
||||
print(("insert: %s"):format(table_str(insert)))
|
||||
print(("before: %s"):format(table_str(into)))
|
||||
insert_into(insert, into, pos)
|
||||
print(("after: %s"):format(table_str(into)))
|
||||
print("------------------------------")
|
||||
end
|
||||
|
||||
test({5, 6, 7}, {1, 2, 3, 10, 11}, 4)
|
||||
|
||||
test({"a", "b", "c"}, { "a", "b", "c", "d", "e" }, 5)
|
||||
|
||||
test({"brave", "new"}, {"hello", "world"}, 2)
|
||||
Reference in New Issue
Block a user