How to resolve the algorithm Multi-dimensional array step by step in the Lua programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Multi-dimensional array step by step in the Lua programming language
Table of Contents
Problem Statement
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to:
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Multi-dimensional array step by step in the Lua programming language
Source code in the lua programming language
-- Variadic, first argument is the value with which to populate the array.
function multiArray (initVal, ...)
local function copy (t)
local new = {}
for k, v in pairs(t) do
if type(v) == "table" then
new[k] = copy(v)
else
new[k] = v
end
end
return new
end
local dimensions, arr, newArr = {...}, {}
for i = 1, dimensions[#dimensions] do table.insert(arr, initVal) end
for d = #dimensions - 1, 1, -1 do
newArr = {}
for i = 1, dimensions[d] do table.insert(newArr, copy(arr)) end
arr = copy(newArr)
end
return arr
end
-- Function to print out the specific example created here
function show4dArray (a)
print("\nPrinting 4D array in 2D...")
for k, v in ipairs(a) do
print(k)
for l, w in ipairs(v) do
print("\t" .. l)
for m, x in ipairs(w) do
print("\t", m, unpack(x))
end
end
end
end
-- Main procedure
local t = multiArray("a", 2, 3, 4, 5)
show4dArray(t)
t[1][1][1][1] = true
show4dArray(t)
You may also check:How to resolve the algorithm Matrix transposition step by step in the APL programming language
You may also check:How to resolve the algorithm Function composition step by step in the Pascal programming language
You may also check:How to resolve the algorithm Partial function application step by step in the C programming language
You may also check:How to resolve the algorithm Binary digits step by step in the Quackery programming language
You may also check:How to resolve the algorithm Last letter-first letter step by step in the BBC BASIC programming language