M
M
MarsFM2018-02-06 11:34:11
Swift
MarsFM, 2018-02-06 11:34:11

How to make a multidimensional array from a one-dimensional array?

Plz tell me how to convert a one-dimensional array into a multi-dimensional one?
8 arrays of 4 elements

var 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","25", "26", "27","28", "29", "30","31", "32"]

var result = ()
var k = 0
for i in 0..<8  {
    for j in 0..<4 {
        result[i].append(arr[k])
        k += 1
    }
}

print(result)

I understand that the array is empty, so we can not access by index. But I don't know how to set the length as in java

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
doublench21, 2018-02-06
@sportredwhite

var 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", "25", "26", "27", "28", "29", "30",
    "31", "32"
]

var res = ()
for x in stride(from: 0, through: 31, by: 4) {
    res.append(Array(arr[x...x + 3]))
}

B
briahas, 2018-02-15
@briahas

The internets (stackoverflow) found a similar solution:

extension Array {
    func chunked(by chunkSize: Int) ->  {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question