matiastofteby matiastofteby - 1 year ago 119
Swift Question

Averaging elements in array of arrays by index using functional programming

I have an array of arrays of Doubles. For example:

let mceGain = [[3,4,5],[7,4,3],[12,10,7]] // Written as integers for simplicity here


I would now like to average the elements in the different arrays with corresponding indexes. So I would have an output looking somewhat like this:

//firstAvg: (3+7+12)/3 = 7.33
//secondAvg: (4+4+10)/3 = 6
//thirdAvg: (5+3+7)/3 = 5


Then finally I would like to store these averages in a simpler array:

//mceGain: [7.33,6,5]


I have tried to do this with a double for-loop with a switch-statement inside, but this seems to be unnecessarily complicated. I assume the same result could be achieved using a combination of
reduce()
,
map()
and
filter()
, but I cannot seem to wrap my head around it.

Answer Source

This should answer your comment below

let elms: [[Double]] = [[3, 5, 3], [4, 4, 10] , [5, 3, 7]]

func averageByIndex(elms:[[Double]]) -> [Double]? {
    guard let length = elms.first?.count else { return []}

    // check all the elements have the same length, otherwise returns nil
    guard !elms.contains(where:{ $0.count != length }) else { return nil }

    return (0..<length).map { index in
        let sum = elms.map { $0[index] }.reduce(0, +)
        return sum / Double(elms.count)
    }
}

if let averages = averageByIndex(elms: elms) {
    print(averages) // [4.0, 4.0, 6.666666666666667]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download