且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按索引移动数组中的元素

更新时间:2023-12-06 17:33:04

您可以使用范围下标并连接结果。这会给你你正在寻找的东西,名字类似于标准库:

 扩展数组{
func shiftRight(var amount:Int = 1) - > [元素] {
assert(-count ... count〜= amount,移位量越界)
如果数量 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]

您可以从返回 Array(后缀(count - amount)+前缀(amount))而不是下标, shiftRight()


Given array of n elements, i.e.

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

I can write an extension to the Array so I can modify array to achieve this output: [2, 3, 4, 5, 1]:

  mutating func shiftRight() {
    append(removeFirst())
  }

Is there a way to implement such a function that would shift array by any index, positive or negative. I can implement this function in imperative style with if-else clauses, but what I am looking for is functional implementation.

The algorithm is simple:

  1. Split array into two by the index provided
  2. append first array to the end of the second

Is there any way to implement it in functional style?

The code I've finished with:

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])
  }
}

You can use ranged subscripting and concatenate the results. This will give you what you're looking for, with names similar to the standard library:

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]

Instead of subscripting, you could also return Array(suffix(count - amount) + prefix(amount)) from shiftRight().