按索引移动数组中的元素 [英] Shift elements in array by index

查看:35
本文介绍了按索引移动数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定 n 个元素的数组,即

Given array of n elements, i.e.

var 数组 = [1, 2, 3, 4, 5]

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

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

有没有办法实现这样一个函数,可以将数组移动任何索引,正数或负数.我可以使用 if-else 子句以命令式风格实现这个函数,但我要寻找的是函数式实现.

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.

算法很简单:

  1. 根据提供的索引将数组一分为二
  2. 将第一个数组附加到第二个数组的末尾

有什么方法可以实现函数式风格吗?

Is there any way to implement it in functional style?

我已经完成的代码:

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]

除了下标之外,您还可以从 shiftRight() 返回 Array(suffix(count - amount) + prefix(amount)).

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

这篇关于按索引移动数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆