Created
May 17, 2020 15:16
-
-
Save bennokress/a12f967e809575be3820c76578640143 to your computer and use it in GitHub Desktop.
Adjustment of my answer on Stack Overflow for a new comment: https://stackoverflow.com/questions/31554670/shift-swift-array/44739098?noredirect=1#comment109386944_44739098
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Array { | |
func shifted(by shiftAmount: Int) -> Array<Element> { | |
// 1 | |
guard self.count > 0, (shiftAmount % self.count) != 0 else { return self } | |
// 2 | |
let moduloShiftAmount = shiftAmount % self.count | |
let negativeShift = shiftAmount < 0 | |
let effectiveShiftAmount = negativeShift ? moduloShiftAmount + self.count : moduloShiftAmount | |
// 3 | |
let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= self.count ? $0 + effectiveShiftAmount - self.count : $0 + effectiveShiftAmount } | |
// 4 | |
return self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element } | |
} | |
mutating func shifting(by shiftAmount: Int) { | |
// 1 | |
guard self.count > 0, (shiftAmount % self.count) != 0 else { return } | |
// 2 | |
let moduloShiftAmount = shiftAmount % self.count | |
let negativeShift = shiftAmount < 0 | |
let effectiveShiftAmount = negativeShift ? moduloShiftAmount + self.count : moduloShiftAmount | |
// 3 | |
let copy = self | |
let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= copy.count ? $0 + effectiveShiftAmount - copy.count : $0 + effectiveShiftAmount } | |
// 4 | |
self = self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element } | |
} | |
} | |
let colorArray = [ | |
UIColor.red, | |
UIColor.orange, | |
UIColor.yellow, | |
UIColor.green, | |
UIColor.blue | |
] | |
let shiftedColorArray = [ | |
UIColor.green, | |
UIColor.blue, | |
UIColor.red, | |
UIColor.orange, | |
UIColor.yellow | |
] | |
colorArray.shifted(by: 2) == shiftedColorArray // returns true | |
[1,2,3,4,5,6,7].shifted(by: -23) // returns [3,4,5,6,7,1,2] | |
var testArray = [1,2,3,4,5,6,7] | |
testArray.shifting(by: -23) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment