Rotate Array in Swift

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

    If anybody lands here after watching the Embracing Algorithms WWDC18 session by David Abrahams, here is one of the implementations of rotate from the swift/test/Prototypes/Algorithms.swift file.

    extension MutableCollection where Self: BidirectionalCollection {
        /// Rotates the elements of the collection so that the element
        /// at `middle` ends up first.
        ///
        /// - Returns: The new index of the element that was first
        ///   pre-rotation.
        /// **- Complexity: O(*n*)**
        @discardableResult
        public mutating func rotate(shiftingToStart middle: Index) -> Index {
            self[..

    This algorithms depends on reverseUntil(:) defined in the same file

    extension MutableCollection where Self: BidirectionalCollection {
    
    /// Reverses the elements of the collection, moving from each end until
    /// `limit` is reached from either direction. The returned indices are the
    /// start and end of the range of unreversed elements.
    ///
    ///     Input:
    ///     [a b c d e f g h i j k l m n o p]
    ///             ^
    ///           limit
    ///     Output:
    ///     [p o n m e f g h i j k l d c b a]
    ///             ^               ^
    ///             f               l
    ///
    /// - Postcondition: For returned indices `(f, l)`:
    ///   `f == limit || l == limit`
    @inline(__always)
    @discardableResult
    internal mutating func _reverseUntil(_ limit: Index) -> (Index, Index) {
        var f = startIndex
        var l = endIndex
        while f != limit && l != limit {
            formIndex(before: &l)
            swapAt(f, l)
            formIndex(after: &f)
        }
        return (f, l)
    }
    }
        
    

提交回复
热议问题