我想将数字加起来并每4个元素打印一次,但是我无法使用stride函数来解决问题,如果我使用的方法错误,请解释一个更好的方法
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13]
func addNumbersByStride(){
var output = Stride...
//first output = 1+2+3+4 = 10
//second output = 5+6+7+8 = 26 and so on
print(output)
}
答案 0 :(得分:0)
您可以先将数组拆分为多个块,然后将这些块加起来:
awk
如果原始数组的长度不能被4整除,如果您想丢弃最后的和,则可以添加如下if语句:
extension Array {
// split array into chunks of n
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
// add each chunk up:
let results = numbers.chunked(into: 4).map { $0.reduce(0, +) }
答案 1 :(得分:0)
这是一个非常基本的解决方案,也许不太优雅。首先计算并打印每组4个元素的总和
var sum = 0
var count = 0
for n in stride(from: 4, to: numbers.count, by: 4) {
sum = 0
for i in n-4..<n {
sum += numbers[i]
}
count = n
print(sum)
}
然后计算剩余元素的总和
sum = 0
for n in count..<numbers.count {
sum += numbers[n]
}
print(sum)
答案 2 :(得分:0)
似乎您想使用跨步...
public T orElse(T other) {
return value != null ? value : other;
}
打印
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13]
let by = 4
let i = stride(from: arr.startIndex, to: arr.endIndex, by: by)
var j = i.makeIterator()
while let n = j.next() {
let e = min(n.advanced(by: by), arr.endIndex)
let sum = arr[n..<e].reduce(0, +)
print("summ of arr[\(n)..<\(e)]", sum)
}