Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse array by group size

Tags:

arrays

swift

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
    }
}
like image 761
Oxthor Avatar asked Dec 27 '17 08:12

Oxthor


People also ask

How do you reverse the order of an array?

The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.


1 Answers

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]
like image 119
Andrea Mugnaini Avatar answered Sep 20 '22 13:09

Andrea Mugnaini