按索引移位数组中的元素

Ric*_*hiy 13 arrays generics ios swift

给定n个元素的数组,即

var array = [1, 2, 3, 4, 5]

我可以写一个扩展名,Array所以我可以修改数组来实现这个输出[2, 3, 4, 5, 1]:

mutating func shiftRight() {
  append(removeFirst())
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这样一个函数,可以通过任何索引,正面或负面移动数组.我可以使用if-else子句以命令式样式实现此函数,但我正在寻找的是功能实现.

算法很简单:

  1. 通过提供的索引将数组拆分为两个
  2. 将第一个数组追加到第二个数组的末尾

有没有办法在功能风格中实现它?

我完成的代码:

extension Array {
  mutating func shift(var amount: Int) {
    guard -count...count ~= amount else { return }
    if amount < 0 { amount += count }
    self = Array(self[amount ..< count] + self[0 ..< amount])
  }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ook 24

您可以使用远程订阅并连接结果.这将为您提供所需的名称,其名称与标准库类似:

extension Array {
    func shiftRight(var amount: Int = 1) -> [Element] {
        assert(-count...count ~= amount, "Shift amount out of bounds")
        if amount < 0 { amount += count }  // this needs to be >= 0
        return Array(self[amount ..< count] + self[0 ..< amount])
    }

    mutating func shiftRightInPlace(amount: Int = 1) {
        self = shiftRight(amount)
    }
}

Array(1...10).shiftRight()
// [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
Array(1...10).shiftRight(7)
// [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

取而代之的下标,你也可以返回Array(suffix(count - amount) + prefix(amount))shiftRight().


Ima*_*tit 18

使用Swift 3,您只需几行代码即可创建shift(withDistance:)和创建shiftInPlace(withDistance:)方法:

extension Array {

    func shift(withDistance distance: Int = 1) -> Array<Element> {
        let offsetIndex = distance >= 0 ?
            self.index(startIndex, offsetBy: distance, limitedBy: endIndex) :
            self.index(endIndex, offsetBy: distance, limitedBy: startIndex)

        guard let index = offsetIndex else { return self }
        return Array(self[index ..< endIndex] + self[startIndex ..< index])
    }

    mutating func shiftInPlace(withDistance distance: Int = 1) {
        self = shift(withDistance: distance)
    }

}
Run Code Online (Sandbox Code Playgroud)

用法:

let array = Array(1...10)
let newArray = array.shift(withDistance: 3)
print(newArray) // prints: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


Ole*_*lex 2

Swift 算法库中现在有\xe2\x80\x99s 专门用于此目的的函数:rotate(toStartAt:)。详细信息在这里

\n