Search code examples
arraysswiftcoreml

Split a large Vector Equally in Swift


I have a large MLMultiArray of length 15360 values.

Sample:

[14.78125,-0.6308594,5.609375,13.57812,-1.871094,-19.65625,9.5625,8.640625,-2.728516,3.654297,-3.189453,-1.740234...]

Is there a way I can convert this huge array into 120 small MLMultiArrays with 128 elements each without changing the sequence of this array and in the most efficient way possible?

The entire array of 15360 elements is available in this Link


Solution

  • Yes, You can do this with an extension which you can also use it as a general solution:

    extension Array {
        func splited(into size: Int) -> [[Element]] {
            return stride(from: 0, to: count, by: size).map {
                Array(self[$0 ..< Swift.min($0 + size, count)])
            }
        }
    }
    let yourArray = [14.78125,-0.6308594, ...] // 15360 elements of your array
    let result = yourArray.splited(into: 128)