2017-08-09 20 views
1

我有一个数组,我希望能够获得数组中某些整数的总和。它将始终是前2个,前3个或前4个元素,所以它不会占用第一个和最后一个整数,如果这使得它更容易。如何获取数组中的一些(但不是全部)整数的总和

我试过这个代码,但它总结了阵列中的所有整数之前不能找到一种方法来阻止它:

let x = array.reduce(0, +) 

回答

3

你可以使用prefix方法。

let nums = [1, 2, 3, 4, 5] 
let sum = nums.prefix(3).reduce(0, +) 

print(sum) // 6 

如果传递到前缀的值大于nums.count时,前缀将自动返回整个数组。

nums.prefix(10).reduce(0, +) // 15 
+0

谢谢这真是棒极了! – StefWG

1

尝试切片阵列:

// array[lowerBound..<upperBound] ignore upperBound 
// array[lowerBound...upperBound] include upperBound 

// Examples: 

// Change 2 for the starting index you want to include 
array[2..<array.count].reduce(0,+) 

array[0..<array.count-2].reduce(0,+) 

// Be careful with upper/lower bounds 
0

这里是(0包容,索引开始)总结了给定的指标之间Int秒的数组元素的函数:

let numbers = [1,2,3,4,5,6,7,8,9,10] 
func sumUpRange(numbers:[Int], from:Int, to:Int)->Int{ 
    return numbers.enumerated().filter({ index, num in index >= from && index <= to}).map{$0.1}.reduce(0,+) 
} 
sumUpRange(numbers: numbers, from: 1, to: 3) //output is 2+3+4=9 
相关问题