Skip to content

Instantly share code, notes, and snippets.

@marcinkuptel
Last active February 6, 2016 15:32
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 marcinkuptel/c1ec4f9804c2f9ad1bb1 to your computer and use it in GitHub Desktop.
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.
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