给定 n 个元素的数组,即
var 数组 = [1, 2, 3, 4, 5]
我可以为 Array
编写一个扩展,这样我就可以修改数组来实现此输出:[2, 3, 4, 5, 1]
:
mutating func shiftRight() {
append(removeFirst())
}
有没有办法实现这样一个函数,可以按任何索引(正数或负数)移动数组。我可以使用 if-else
子句以命令式方式实现此函数,但我正在寻找的是函数式实现。
算法很简单:
- 根据提供的索引将数组分成两部分
- 将第一个数组附加到第二个数组的末尾
有没有办法以函数式的方式实现它?
我完成的代码:
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])
}
}
最佳答案
您可以使用范围下标并连接结果。这将为您提供您正在寻找的内容,其名称类似于标准库:
extension Array {
func shiftRight(var amount: Int = 1) -> [Element] {
guard count > 0 else { return self }
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]
您还可以从 shiftRight()
返回 Array(suffix(count - amount) + prefix(amount))
,而不是下标。
关于ios - 按索引移动数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751122/