Rotate Array in Swift

前端 未结 10 767
终归单人心
终归单人心 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:57

    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"]
    
    

提交回复
热议问题