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
}
}
The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With