|
Post by cntkillme on Jun 29, 2017 9:07:15 GMT
So here's another fun little Lua challenge:
Challenge Write a function that accepts an array of integers (dimensions) and returns an N-dimensional array in which N = #dimensions and each integer in this array makes up the boundary of each dimension. All data should be set to 0 in the returned array.
Example
local map = ConstructNDimensionalArray({ 5, 1, 3, 4 }) print(map[1][1][1][1]) --> 0 print(map[5][1][3][4]) --> 0 Will construct a 4-dimensional array (a 5x1x3x4 array) and print out the first and last values.
Constraints 0 < N < inf 0 < D < inf for all values D in Dimensions
|
|
|
Post by Bit on Jun 30, 2017 21:37:24 GMT
Sounds simple enough, if I understood it properly. This may not be the most efficient or anything but AFAIK it works.
local ConstructNDimensionalArray do local dotolast;dotolast=function(tab,exec) if #tab==0 then exec(tab) else for _,v in pairs(tab) do dotolast(v,exec) end end end ConstructNDimensionalArray=function(Table) local Result={} local D=#Table for Dim=1,D do local DLen=Table[Dim] dotolast(Result,function(tab) for i=1,DLen do if Dim==D then tab[i]=0 else tab[i]={} end end end) end return Result end end
local map = ConstructNDimensionalArray({ 5, 1, 3, 4 }) print(map[1][1][1][1]) --> 0 print(map[5][1][3][4]) --> 0
|
|
|
Post by cntkillme on Jul 6, 2017 9:51:57 GMT
Ok here was my solution, apparently nobody forums here since I have like probably less than 20 unique views:
local function NDimensionalArray(dimensions, initial, dimIdx) initial = initial or ' ' dimIdx = dimIdx or 1 if dimIdx <= #dimensions then local size = dimensions[dimIdx] local data = { }
for idx = 1, size do data[idx] = NDimensionalArray(dimensions, initial, dimIdx + 1) end return data else return initial end end
return NDimensionalArray
|
|