While exploring algorithms in Swift, couldn\'t find algorithm for array rotation in swift without using funcs shiftLeft
/ shiftRight
.
C has
To be complete, the rotation function should support negative (right) rotations and rotating more than the array's size
extension Array
{
mutating func rotateLeft(by rotations:Int)
{
// rotation irrelevant when less than 2 elements
if count < 2 { return }
// effective left rotation for negative and > count
let rotations = (rotations%count + count) % count
// no use rotating by zero
if rotations == 0 { return }
// rotate
(1..