[Solved] how to print array’s even numbers sum/avarage and odd numbers sum/average?


O(n)

You can do it in one sweep :

let (oddsSum, oddsCount, evensSum, evensCount) = a.reduce(into:(0, 0, 0, 0)) { tuple, element in
    if element % 2 != 0 {
        tuple.0 += element
        tuple.1 += 1
    } else {
        tuple.2 += element
        tuple.3 += 1
    }
}

let oddsAverage = oddsCount == 0 ? 0.0 : Double(oddsSum) / Double(oddsCount)
let evensAverage = evensCount == 0 ? 0.0 : Double(evensSum) / Double(evensCount) 

Which would yield the following results :

oddsSum       //169 
oddsAverage   //56.33333333333334 
evensSum      //364 
evensAverage  //52

Two arrays

You can create two arrays of odds and evens like so :

let a = [32, 37, 68, 66, 97, 38, 16, 86, 35, 58]

let (odds, evens) = a.reduce(into:([Int](), [Int]())) { tuple, element in
    if element % 2 != 0 {
        tuple.0.append(element)
    } else {
        tuple.1.append(element)
    }
}

odds and evens are two arrays of integers: [Int].


Sums

To calculate the sums :

let oddsSum = odds.reduce(0, +)           //169
let evensSum = odds.reduce(0, +)          //364

You can also use cblas_dasum(_:_:_:) from the Accelerate framework, which is faster than reduce :

import Accelerate

var (odds, evens) = a.reduce(into:([Double](), [Double]())) { tuple, element in
    if element % 2 != 0 {
        tuple.0.append(Double(element))
    } else {
        tuple.1.append(Double(element))
    }
}

var oddSum = Int(cblas_dasum(Int32(odds.count), &odds, 1))
print(oddSum)     //169

var evenSum = Int(cblas_dasum(Int32(evens.count), &evens, 1))
print(evenSum)    //364

Averages

The averages are the sums divided by the number of elements in each array.

let oddsAverage = odds.isEmpty ? 0.0 : Double(oddsSum) / Double(odds.count)    //56.33333333333334
let evensAverage = evens.isEmpty ? 0.0 : Double(evensSum) / Double(evens.count) //52

Or you can use vDSP_meanvD(_:_:_:_:) from the Accelerate framework, which is faster than calculating the sum and then dividing by the count :

import Accelerate

var (odds, evens) = a.reduce(into:([Double](), [Double]())) { tuple, element in
    if element % 2 != 0 {
        tuple.0.append(Double(element))
    } else {
        tuple.1.append(Double(element))
    }
}

var oddAvg = 0.0
vDSP_meanvD(&odds, 1, &oddAvg, vDSP_Length(odds.count))
print(oddAvg)     //56.333333333333336

var evenAvg = 0.0
vDSP_meanvD(&evens, 1, &evenAvg, vDSP_Length(evens.count))
print(evenAvg)    //52.0

solved how to print array’s even numbers sum/avarage and odd numbers sum/average?