Home > Back-end >  Sum an array of arrays by position resulting in one array in Swift
Sum an array of arrays by position resulting in one array in Swift

Time:07-11

I have an array of arrays of Int and I want to sum every value within all the values in the same position in a performing way. For example:

let array: [[Int]] = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

The result should be:

let result: [Int] = [11, 14, 11, 9]

If this is too complex, I can make all subarrays to have the same amount of elements.

My current soultion is the following but I believe it has to be a cleaner and more efficient way of doing it:

func sumElementsInSubArrays(_ array: [[Int]]) -> [Int] {
        var result: [Int] = []
        for subarray in array {
            for (i, value) in subarray.enumerated() {
                if result.count > (i) {
                    result[i] = result[i]   value
                } else {
                    result[i] = value
                }
            }
        }
        return result
    }

CodePudding user response:

There may be several ways like HOF to deal with this situation but if you are new to it like me , you can do it like this :

Considering all the subArrays to have same number of element :

let array = [[1, 2, 3, 4], [5, 2, 7, 0] , [1, 7, 9, 4]]

        var finalArray = [Int]()
        for i in 0..<(array.first?.count ?? 0) {
            var aElement = 0
            array.forEach { aArray in
                aElement  = aArray[i]
            }
            finalArray.append(aElement)
        }

//Final array should look like this at this point : [7, 11, 19, 8]

CodePudding user response:

You could use a couple of nested loops (I don't think performance wise using reduce would be faster, thought it may look better/debatably be better for readability):

func sumElementsInSubArrays(_ array: [[Int]]) -> [Int] {
    var result: [Int] = []
    for subarray in array {
        for (i, value) in subarray.enumerated() {
            if result.count > i {
                result[i]  = value
            } else {
                result.append(value)
            }
        }
    }
    return result
}

print(sumElementsInSubArrays([[1, 2, 3], [4, 5], [6, 7, 8, 9]]))
print(sumElementsInSubArrays([]))
print(sumElementsInSubArrays([[]]))

Output:

[11, 14, 11, 9]
[]
[]
  • Related