I have a flat array as shown below that represents a 3D array. The example prints the shape of the array as (2, 3, 4)
which means there are two arrays each with a size of 3-by-4 elements.
let arr = [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]] let shape = (arr.count, arr[0].count, arr[0][0].count) print("shape is", shape)
I would like to calculate the shape of this array (or any N-dimensional array) using a function. My failed attempt is shown below.
func getShape<T>(_ arrays: [T]...) -> [Int] { if type(of: arrays) != Array<T>.self { return [arrays.count] } var shape = [Int]() for subArray in arrays { shape.append(subArray.count) } return shape } let s = getShape(arr) print("shape is", s)
The first problem seems to be that the variadic input parameter [T]...
is not being iterated over. It is interpreted as a single array and not an array of arrays. I also think the function needs to be recursive to properly calculate the shape. But before I can do that, I need to figure out how to properly define the input parameter. Does anyone have suggestions on how to calculate the shape of a flat array that represents an N-dimensional array?