Rotate Array in Swift

前端 未结 10 841
终归单人心
终归单人心 2021-01-05 16:45

While exploring algorithms in Swift, couldn\'t find algorithm for array rotation in swift without using funcs shiftLeft / shiftRight.

C has

10条回答
  •  难免孤独
    2021-01-05 16:58

    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..

提交回复
热议问题