Home > katas > Sum of positive (8kyu) [Swift]

Sum of positive (8kyu) [Swift]


Chek kata on Codewars

Description:

You get an array of numbers, return the sum of all of the positives ones.

Example [1,-4,7,12] => 1 + 7 + 12 = 20

Note: if there is nothing to sum, the sum is default to 0.

Solution 1.1

Let's use reduce method to solve this task. It executes a reducer function (that you provide) on each element of the array, resulting in single output value. It is almost a textbook example for reducer.

func sumOfPositives (_ numbers: [Int] ) -> Int {
    return numbers.reduce(0, {accumulator, current in accumulator + (current > 0 ? current : 0)})
}

Solution 1.2

func sumOfPositives (_ numbers: [Int] ) -> Int {
    return numbers.filter{$0 > 0}.reduce(0, +)
}

Solution 1.3

func sumOfPositives (_ numbers: [Int] ) -> Int {
    return numbers.reduce(0){$0 + max($1, 0)}
}

Solution 2.1

Another approach will be to loop over the array and sum all positive numbers.

func sumOfPositives (_ numbers: [Int] ) -> Int {
    var sum: Int = 0

    for number in numbers {
        if number > 0 {
            sum += number
        }
    }

    return sum
}

Solution 2.2

func sumOfPositives (_ numbers: [Int] ) -> Int {
    var sum: Int = 0

    for number in numbers where number > 0 {
       sum += number
    }

    return sum
}
© 2021, Andrew Losseff