While exploring algorithms in Swift, couldn\'t find algorithm for array rotation in swift without using funcs shiftLeft
/ shiftRight
.
C has
here is a way to rotate left or right. Just call rotate on your array as shown. This does not mutate the array, if you wish to mutate the array, set the array equal to the rotation.
extension Array {
func rotate(moveRight: Bool, numOfRotations: Int) -> Array{
var arr = self
var i = 0
while i < numOfRotations {
if moveRight {
arr.insert(arr.remove(at: arr.count - 1), at: 0)
} else {
arr.append(arr.remove(at: 0))
}
i += 1
}
return arr
}
}
var arr = ["a","b","c","d","e"]
print(arr.rotate(moveRight: true, numOfRotations: 2))
// ["d", "e", "a", "b", "c"]
print(arr)
// ["a", "b", "c", "d", "e"]
arr = arr.rotate(moveRight: true, numOfRotations: 2)
print(arr)
// ["d", "e", "a", "b", "c"]