Shift Swift数组

Zel*_*lko 4 arrays ios swift

一系列的颜色

let colorArray = [
    UIColor.redColor(),
    UIColor.orangeColor(),
    UIColor.yellowColor(),
    UIColor.greenColor(),
    UIColor.blueColor()
]
Run Code Online (Sandbox Code Playgroud)

目标是转移阵列:

  1. 从不同的颜色开始.
  2. 保持颜色的循环顺序.

示例#1

如果我们想要以橙色(原始数组中索引1处的颜色)开始,则数组将如下所示:

let colorArray = [
    UIColor.orangeColor(),
    UIColor.yellowColor(),
    UIColor.greenColor(),
    UIColor.blueColor(),
    UIColor.redColor(),
]
Run Code Online (Sandbox Code Playgroud)

例#2

如果我们想要以绿色(原始数组中索引3处的颜色)开始,则数组将如下所示:

let colorArray = [
    UIColor.greenColor(),
    UIColor.blueColor(),
    UIColor.redColor(),
    UIColor.orangeColor(),
    UIColor.yellowColor()
]
Run Code Online (Sandbox Code Playgroud)

ziz*_*utg 8

我知道这可能会迟到.但是旋转或移动阵列最简单的方法是

func shifter(shiftIndex: Int) {
   let strArr: [String] = ["a","b","c","d"]
   var newArr = strArr[shiftIndex..<strArr.count]
   newArr += strArr[0..<shiftIndex]       
   println(newArr)  }

shifter(2) //[c, d, a, b] you can modify the function to take array as input
Run Code Online (Sandbox Code Playgroud)


Ben*_*ess 5

我想出了简短的Swift 3和4解决方案:

extension Array {

    func shifted(by shiftAmount: Int) -> Array<Element> {

        // 1
        guard self.count > 0, (shiftAmount % self.count) != 0 else { return self }

        // 2
        let moduloShiftAmount = shiftAmount % self.count
        let negativeShift = shiftAmount < 0
        let effectiveShiftAmount = negativeShift ? moduloShiftAmount + self.count : moduloShiftAmount

        // 3
        let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= self.count ? $0 + effectiveShiftAmount - self.count : $0 + effectiveShiftAmount }

        // 4
        return self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element }

    }

}
Run Code Online (Sandbox Code Playgroud)

说明:

  1. 没有元素且没有移位的数组会立即返回原始数组的标识
  2. 为了获得有效的移位量而与函数传递的量无关,我们进行一些模运算以消除移位,该移位会使数组中的元素旋转一次以上(例如,在具有5个对象的数组中,移位为+7)与+2的偏移相同)。因为我们一直想向右移动,所以要使用一个简单的函数而不是两个函数,必须处理负输入(例如,在具有5个对象的数组中,-2的移位与移位相同(+3)。因此,我们通过数组的长度来调整模运算的负结果。当然,这三行代码可以合而为一,但是我想让它尽可能地可读。
  3. 现在,我们通过获取$0元素的索引()并通过添加在步骤2中计算出的量来返回已移动的索引来准备实际的移位。如果新的索引落在数组长度之外,则需要将其包裹在最前面。
  4. 最后,我们使用一些技巧将所有准备工作应用到我们的数组:enumerated()给我们提供了一个元组数组[(offset: Int, element: Int)],它只是每个元素和元素本身的原始索引。然后,offset通过应用步骤3中的函数,通过操作(即元素的索引)对枚举数组进行排序。最后,通过将排序后的元素映射回数组,从而摆脱了枚举。

此扩展适用于任何类型的数组。例子:

let colorArray = [
    UIColor.red,
    UIColor.orange,
    UIColor.yellow,
    UIColor.green,
    UIColor.blue
]

let shiftedColorArray = [
    UIColor.green,
    UIColor.blue,
    UIColor.red,
    UIColor.orange,
    UIColor.yellow
]

colorArray.shifted(by: 2) == shiftedColorArray // returns true

[1,2,3,4,5,6,7].shifted(by: -23) // returns [3,4,5,6,7,1,2]
Run Code Online (Sandbox Code Playgroud)