Rotate Array in Swift

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

    We can do it using Array's dropFirst() and dropLast() functions.

    func rotateLeft(arrToRotate: inout [Int], positions: Int){
      if arrToRotate.count == 0 || positions == 0 || positions > arrToRotate.count{
          print("invalid")
          return
      }
      arrToRotate = arrToRotate.dropFirst(positions) + arrToRotate.dropLast(arrToRotate.count-positions)
    }
    
    var numbers : [Int] = [1, 2, 3, 4, 5]
    rotateLeft(arrToRotate: &numbers, positions:2)
    print(numbers)  //prints [3, 4, 5, 1, 2]
    
    0 讨论(0)
  • 2021-01-05 17:14

    You need to consider the scenario such as-

    The number of rotation can be equal/more than the size of array you need to rotate.

    To handle this scenario use modulo operator to find the actual number of rotation as you will find out rotating an array by a number equal to its size result in same array.

        func rotateLeft(array:[Int],numberOfRotation:Int) -> [Int]
        {
         let offset = numberOfRotation % array.count
         let tempResult = array[offset...] + array[..<offset]
         return Array(tempResult)
        }
    
    0 讨论(0)
  • 2021-01-05 17:15

    We can use Slice

    func rotLeft(a: [Int], d: Int) -> [Int] {
        let slice1 = a[..<d]
        let slice2 = a[d...]
        return Array(slice2) + Array(slice1)
    }
    
    print(rotLeft(a:[1, 2, 3, 4, 5], d: 4))
    
    //prints [5, 1, 2, 3, 4]
    
    0 讨论(0)
  • 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..<positions].reverse()
            self[positions..<size].reverse()
            self[0..<size].reverse()
        }
    }
    
    0 讨论(0)
提交回复
热议问题