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

Sum of positive (8kyu) [Dart]


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

Let's use fold method to solve this task.

int positiveSum(List<int> arr) {
  var reducer = (int accumulator, int current) =>
      accumulator + (current > 0 ? current : 0);
  return arr.fold(0, reducer);
}

There are a few variations of this solution. The main difference is how we check if the number is positive or not.

Solution 1.1

import "dart:math";

int positiveSum(List<int> arr) {
  return arr.fold(
      0, (int accumulator, int current) => accumulator + max(current, 0));
}

Solution 1.2

int positiveSum(List<int> arr) {
  return arr
      .where((number) => number > 0)
      .fold(0, (accumulator, current) => accumulator + current);
}

Solution 2

For loop will do the trick as well.

int positiveSum(List<int> arr) {
  int sum = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
      print(arr[i]);
      sum += arr[i];
    }
  }
  return sum;
}

Solution 2.1

int positiveSum(List<int> arr) {
  int sum = 0;
  arr.forEach((int number) => number > 0 ? (sum += number) : 0);
  return sum;
}
© 2021, Andrew Losseff