首页 > 解决方案 > 如何在 Swift 中逐字地获得相等大小的数组切片

问题描述

例如对于 array let array = [1, 3, -5, 2, 6],我想得到这个输出:具有相等大小(N)的数组切片。

如果 N = 2,则输出: [1,3] [3,-5] [-5,2] [2,6]

如果 N = 3,则输出: [1,3,-5] [3,-5,2] [-5,2,6]

///更新我的代码如下,winSize用于定义切片数组的大小,来自readLine()

class windowSize {
    var resultArray = [Int]()

    func execTest() {
        print("please give the window size W and length(S) of array, seperated by space")
        if let firstLine = readLine() {
            let firstLineArray = firstLine.compactMap{Int(String($0))}
            let winSize = firstLineArray[0]

            print("please give the test array with S length")
            if let arr1 = readLine() {
                let arr = arr1.compactMap{Int(String($0))}
                // print(arr)

                // get each slice array with window size length
                let slicedArray = arr.neighbors

                // get max value in each slice array
                for ele in slicedArray {
                    let max = ele.max()
                    resultArray.append(max!)
                }

                print("resultarray", resultArray)
            }
        }
    }
}

extension Collection {
    var neighbors: [SubSequence] {
        guard !isEmpty else { return [] }
        return indices.dropLast().map {
            return self[$0..<(index($0, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex)]
        }
    }
}

windowSize().execTest()

标签: arraysswiftslice

解决方案


您可以迭代您的集合索引删除最后一个并返回每个元素及其后续邻居:

extension Collection {
    var neighbors: [SubSequence] {
        indices.dropLast().map {
            self[$0..<(index($0, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex)]
        }
    }
}

let array = [1, 3, -5, 2, 6]
let chunks = array.neighbors  // [[1, 3], [3, -5], [-5, 2], [2, 6]]
let maxValues = chunks.compactMap{$0.max()}  // [3, 3, 2, 6]

如果您需要两个以上的元素:

extension Collection {
    func customChunk(of n: Int) -> [SubSequence] {
        indices.dropLast(n-1).map {
            self[$0..<(index($0, offsetBy: n, limitedBy: self.endIndex) ?? self.endIndex)]
        }
    }
}

let chunks3 = array.customChunk(of: 3)  // [[1, 3, -5], [3, -5, 2], [-5, 2, 6]]
let maxValues3 = chunks.compactMap{$0.max()}  // [3, 3, 6]

推荐阅读