例如,对于数组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()
这是一个简单的解决方案:
func windows<T>(in a: [T], ofSize w: Int) -> [[T]] {
//You could decide here what you want to return if w is invalid
if w > a.count || w <= 0 {
return []
}
var output = [[T]]()
for i in 0..<a.count-w+1 {
output.append(Array(a[i..<i+w]))
}
return output
}
这是一些用例:
windows(in: [1, 3, -5, 2, 6], ofSize: 2) //[[1, 3], [3, -5], [-5, 2], [2, 6]]
windows(in: [1, 3, -5, 2, 6], ofSize: 3) //[[1, 3, -5], [3, -5, 2], [-5, 2, 6]]
您可以迭代删除最后一个的集合索引,并返回每个元素及其后续的邻居:
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]
array.neighbors // [[1, 3], [3, -5], [-5, 2], [2, 6]]
extension Collection {
func customChunk(of n: Int) -> [[Element]] {
indices.dropLast(n-1).map {
.init(self[$0..<(index($0, offsetBy: n, limitedBy: self.endIndex) ?? self.endIndex)])
}
}
}
let array = [1, 3, -5, 2, 6]
array.customChunk(of: 3) // [[1, 3, -5], [3, -5, 2], [-5, 2, 6]]