Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spilt Array into pairs

Tags:

arrays

swift

I am trying to split array into pairs. I am able to split into consecutive pair but I want to split into pair which includes previous value as mentioned in Results

Logic to split in consecutive pair, which I tried.

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

Array:

["1", "2", "3", "4", "5", "6", "7", "8", "9"]

Results:

[["1", "2"], ["2", "3"], ["3", "4"], ["4", "5"], ["6", "7"], ["7", "8"], ["8", "9"]]
like image 424
Santosh Singh Avatar asked Feb 26 '26 19:02

Santosh Singh


1 Answers

How about this:

let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

let pairs = Array(zip(a, a.dropFirst())).map {[$0.0, $0.1] }

print(pairs)

That outputs

[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

Edit:

If you want arbitrary chunk-size, you could write the extension like this:

extension Array {
    func chunks(_ chunkSize: Int, includePartialChunk: Bool = true) -> [[Element]] {
        var indexes = Array<Int>(stride(from: 0, to: count, by: chunkSize - 1))
        if includePartialChunk,
           let last = indexes.last,
           last < count - 1 {
            indexes.append(count-1)
        }
        return zip(indexes, indexes.dropFirst()).map {Array(self[$0.0...$0.1])}
    }
}

Use the parameter includePartialChunk to tell the function if you want to include a "partial chunk" at the end when the array size is not an even multiple of the chunk-size. If true (The default) it returns a last chunk that is smaller than chunkSize but goes to the end of the array. If false, it only returns full-sized chunks, but will skip array elements at the end that don't fit into a full-sized chunk.

(I'll have to study Leo's UnfoldSequence version and see if I can adapt my code to that.)

like image 149
Duncan C Avatar answered Feb 28 '26 09:02

Duncan C