9

I was trying to solve this challenge: reverse an array of elements by groups given a group size.

Given Array: [1, 2, 3, 4, 5, 6]

Desired Result (group size of 3): [4, 5, 6, 1, 2, 3]

If last group has less elements than the group size, then just add them and finish, as follows:

Given Array: [1, 2, 3, 4, 5, 6, 7]

Desired Result: [5, 6, 7, 2, 3, 4, 1]

I tried this and it is working, but it looks kinda weird for me. Can anyone help me find a cleaner or much more intuitive solution?

extension Array {
    func reverse(groupSize: Int) -> [Element] {
        var reversed = [Element]()
        let groups = count / groupSize

        for group in 0...groups {
            let lowerBound = count - group * groupSize - groupSize
            let upperBound = count - 1 - group * groupSize

            if lowerBound >= 0 {
                reversed += Array(self[lowerBound...upperBound])
            } else {
                reversed += Array(self[0...upperBound])
            }
        }

        return reversed
    }
}
0

4 Answers 4

2

The following solution is based on a combo of stride+map:

let groupSize = 3
let array = [1, 2, 3, 4, 5, 6]
let reversedArray = Array(array.reversed())
let result = stride(from: 0, to: reversedArray.count, by: groupSize).map {
  reversedArray[$0 ..< min($0 + groupSize, reversedArray.count)].reversed()
}.reduce([Int](), +)
print(result) //  [4, 5, 6, 1, 2, 3]
2
  • You can add result.reduce([Int](), +) to make it become single array
    – Tj3n
    Dec 27, 2017 at 9:55
  • clear and concise, will take into account with @Tj3n comment
    – Oxthor
    Dec 27, 2017 at 10:18
1

You could say:

extension Array {

  func groupedReversing(stride: Int) -> [Element] {
    precondition(stride > 0, "stride must be > 0")

    return Swift.stride(from: count, to: 0, by: -stride)
            .flatMap { self[Swift.max(0, $0 - stride) ..< $0] }
  }
}

let result = Array(1 ... 7).groupedReversing(stride: 3)
print(result) // [5, 6, 7, 2, 3, 4, 1]

We're using stride(from:through:by:) to iterate from array.count (inclusive) to 0 (exclusive) in increments of (minus) the stride. The Swift. prefix is in order to disambiguate it from the obsoleted Swift 2 stride method (which will be gone in Swift 4.1).

Then, we're flat-mapping the index to a slice of the input array that's up to stride elements long (truncating at the beginning of the array as we clamp the lower index to 0). And because this is flatMap, the resulting slices are concatenated into a single resulting array.

You could also implement a fully generic version across Sequence by first providing an implementation on BidirectionalCollection, advancing indices backwards and appending slices into a resulting array:

extension BidirectionalCollection {

  func groupedReversing(stride: Int) -> [Element] {

    precondition(stride > 0, "stride must be > 0")

    var result: [Element] = []
    result.reserveCapacity(numericCast(count))

    var upper = endIndex
    while upper != startIndex {
      // get the next lower bound for the slice, stopping at the start index.
      let lower = index(upper, offsetBy: -numericCast(stride),
                        limitedBy: startIndex) ?? startIndex
      result += self[lower ..< upper]
      upper = lower
    }
    return result
  }
}

and then implement an overload on Sequence that first converts to an array, and then forwards onto the above implementation:

extension Sequence {
  func groupedReversing(stride: Int) -> [Element] {
    return Array(self).groupedReversing(stride: stride)
  }
}

Now you can call it on, for example, a CountableClosedRange without first having to convert it to an array:

let result = (1 ... 7).groupedReversing(stride: 3)
print(result) // [5, 6, 7, 2, 3, 4, 1]
1

I think your function is okay, not sure what you meant by weird tbh, can separate to chunk or add each elements in reversed way ,but logic is same anyway, just need to mind the performance/complexity of each ways:

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

extension Array {
    func reverse(group: Int) -> [Element] {
        guard group > 1 else { return self.reversed() }
        var new = [Element]()
        for i in stride(from: self.count-1, through: 0, by: -group) {
            let k = i-group+1 < 0 ? 0 : i-group+1
            for j in k...i {
                new.append(self[j])
            }
        }
        return new
    }
}

a.reverse(group: 4) //[8, 9, 10, 11, 4, 5, 6, 7, 1, 2, 3]
1
  • 1
    You could also say let k = Swift.max(0, i - group + 1) instead of let k = i-group+1 < 0 ? 0 : i-group+1, and new += self[k ... i] instead of for j in k...i { new.append(self[j]) } :)
    – Hamish
    Dec 27, 2017 at 18:55
0

The two following Swift 5 code snippets show how to implement a Collection or Array extension method in order to chunked it, reverse it then flatten it into a new array.


#1. Using AnyIterator and Sequence joined()

extension Collection {

    func reverseFlattenChunked(by distance: Int) -> [Element] {
        precondition(distance > 0, "distance must be greater than 0")

        var index = endIndex
        let iterator = AnyIterator({ () -> SubSequence? in
            let newIndex = self.index(index, offsetBy: -distance, limitedBy: self.startIndex) ?? self.startIndex
            defer { index = newIndex }
            return index != self.startIndex ? self[newIndex ..< index] : nil
        })

        return Array(iterator.joined())
    }

}

Usage:

let array = ["1", "2", "3", "4", "5", "6", "7"]
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: ["5", "6", "7", "2", "3", "4", "1"]

let array: [String] = ["1", "2", "3", "4", "5", "6"]
let newArray = array.reverseFlattenChunked(by: 2)
print(newArray) // prints: ["5", "6", "3", "4", "1", "2"]

let array: [String] = []
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: []

#2. Using stride(from:to:by:) and Sequence flatMap(_:)

extension Array {

    func reverseFlattenChunked(by distance: Int) -> [Element] {
        precondition(distance > 0, "distance must be greater than 0")

        let indicesSequence = stride(from: self.endIndex, to: self.startIndex, by: -distance)
        let array = indicesSequence.flatMap({ (index) -> SubSequence in
            let advancedIndex = self.index(index, offsetBy: -distance, limitedBy: self.startIndex) ?? self.startIndex
            // let advancedIndex = index.advanced(by: -distance) <= self.startIndex ? self.startIndex : index.advanced(by: -distance) // also works
            return self[advancedIndex ..< index]
        })

        return array
    }

}

Usage:

let array = ["1", "2", "3", "4", "5", "6", "7"]
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: ["5", "6", "7", "2", "3", "4", "1"]

let array: [String] = ["1", "2", "3", "4", "5", "6"]
let newArray = array.reverseFlattenChunked(by: 2)
print(newArray) // prints: ["5", "6", "3", "4", "1", "2"]

let array: [String] = []
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.