我正在试图弄清楚如何将数组拆分成重叠的块.
例如,以下是输入:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
个
这是预期的输出(块大小为3):
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]
个
我开始使用STRIDE(通过与Swift的黑客攻击):
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
这当然会给出不正确的输出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
个
我找不到stride
的任何变体来获得预期结果,所以就这样做了,使用了两个嵌套的for-loops
:
extension Array {
func chunked2(into size: Int) -> [[Element]] {
var result: [[Element]] = []
for i in 0...self.count {
var chunk: [Element] = []
for j in i..<i+size {
if j < self.count {
chunk.append(self[j])
}
}
if chunk.count == size {
result.append(chunk)
}
}
return result
}
}
这是可行的,并给出了预期的结果.
问:我想知道我是否可以用一种更"快速"的方式重写它,使用像stride
、map
、也许reduce
这样的函数或其他我遗漏的函数?