Skip to content

Instantly share code, notes, and snippets.

@Nirma
Last active December 25, 2015 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nirma/ff92b89c21ce16d62b42 to your computer and use it in GitHub Desktop.
Save Nirma/ff92b89c21ce16d62b42 to your computer and use it in GitHub Desktop.
enum ShiftDirection {
case Left, Right
}
func shiftBy<T>(shiftDegree: Int, inArray: [T], shiftDirection: ShiftDirection) -> [T] {
guard inArray.count > 2 else {
return inArray
}
let safeShift = (shiftDegree + (shiftDirection == .Right ? (inArray.count - 2) : 0)) % inArray.count
let length: Int = inArray.count
var shiftedArray = [T]()
for pos in 0..<length {
let posNext = (pos + safeShift) % length
shiftedArray += [inArray[posNext]]
}
return shiftedArray
}
func shiftAndCenter<T>(offset: Int, inArray: [T]) -> [T] {
let safeOffset = offset % inArray.count
let middle = (inArray.count / 2) + (inArray.count % 2)
let shiftDegree = (safeOffset + middle) % (inArray.count )
return shiftBy(shiftDegree, inArray: inArray, shiftDirection: .Right)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment