arrays - 如何在 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()
解决方案
您可以迭代您的集合索引删除最后一个并返回每个元素及其后续邻居:
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]
推荐阅读
- r - 使用表函数计算 R 中的样本比例
- firebase - Firebase 电话身份验证:一些用户没有收到 OTP
- javascript - (已解决)将 Ruby ROR 变量传递给 Javascript 小部件脚本的正确方法是什么?
- c# - 如何从 HTML 的下拉列表中获取选定的值到 C#
- spring-boot - JPARepository CPRQ 修改不保存完整对象
- python - Pandas 多索引
- android - Jetpack Compose 使用 Painter 在图像上绘图
- php - 在 URL 和模型关联中带有 id 的 Laravel 资源路由
- python - Pandas groupby mean() 在输出中删除一列
- python - 为什么这个 tf.keras 模型在切片输入上的行为与预期不同?