Rotate Array in Swift

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

    Edit update:

    Swift 5 or later

    extension RangeReplaceableCollection {
        mutating func rotateLeft(positions: Int) {
            let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex
            let slice = self[..

    extension RangeReplaceableCollection {
        mutating func rotateRight(positions: Int) {
            let index = self.index(endIndex, offsetBy: -positions, limitedBy: startIndex) ?? startIndex
            let slice = self[index...]
            removeSubrange(index...)
            insert(contentsOf: slice, at: startIndex)
        }
    }
    

    var test = [1,2,3,4,5,6,7,8,9,10]
    test.rotateLeft(positions: 3)   // [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
    
    var test2 = "1234567890"
    test2.rotateRight(positions: 3)   // "8901234567"
    

提交回复
热议问题