Last active
February 6, 2016 15:32
-
-
Save marcinkuptel/c1ec4f9804c2f9ad1bb1 to your computer and use it in GitHub Desktop.
Algorithm rotating the contents of an array by the number of positions specified as a parameter.
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
extension Array | |
{ | |
mutating func rotateBy(var positions: Int) { | |
positions = positions < 0 ? (self.count - abs(positions) % self.count) : positions % self.count | |
if self.count % 2 == 0 { | |
rotateFrom(0, elements: self.count/2, stride: positions) | |
rotateFrom(1, elements: self.count/2, stride: positions) | |
}else{ | |
rotateFrom(0, elements: self.count, stride: positions) | |
} | |
} | |
private mutating func rotateFrom(position: Int, elements: Int, stride: Int) | |
{ | |
var counter = elements | |
var index = position | |
var toMove = self[index] | |
while counter > 0 | |
{ | |
let toSave = self[(index+stride) % self.count] | |
self[(index+stride) % self.count] = toMove | |
toMove = toSave | |
index = (index+stride) % self.count | |
counter-- | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment