Rotate Array in Swift

前端 未结 10 771
终归单人心
终归单人心 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 17:15

    Why create a reverse function when we already have it in the Swift standard library? My solution (derived from Leo Dabus'):

    extension Array {
        mutating func rotate(positions: Int, size: Int? = nil) {
            let size = size ?? count
            guard positions < count && size <= count else { return }
    
            self[0..

提交回复
热议问题