Skip to content

Instantly share code, notes, and snippets.

@Nirma
Last active Dec 25, 2015
Embed
What would you like to do?
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