Home > Mobile >  how to calculate sum of every n values in a list?
how to calculate sum of every n values in a list?

Time:01-03

I have a list that contains some values I want to calculate the sum of every 4 items in this list and then I have to put it in a list.

for example:

list 1=[1,2,3,4,5,6,7,8]
output= [10,26]

CodePudding user response:

You can play with snippet.

final List<int> list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List<List<int>> subLists = [];

for (int i = 0; i < list.length / 4; i  ) {
  final start = i * 4;
  final end = i * 4   4;
  subLists
      .add(list.sublist(start, end > list.length ? list.length : end));
}

print(subLists); //[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

final results = subLists
    .map((l) => l.reduce((value, element) => value   element))
    .toList();

print(results); //[10, 26, 9]

CodePudding user response:

You can use this custom-made extension method to sum every n in a `List``, just add it inside your file outside your classes :

extension SumEveryExtension on List<num> {
  List<num> sumEvery(int n) {
    num nSumTracker = 0;
    List<num> result = [];
    for (int index = 0; index < length; index  = 1) {
      nSumTracker  = this[index];
      print("current"   nSumTracker.toString());

      if ((index  1) % (n  ) == 0 && index != 0) {
        result.add(nSumTracker);
        nSumTracker = 0;
      }
    }
    return result;
  }
}

And use it in your code like this:

List<int> list = [1, 2, 3, 4, 5, 6, 7, 8];

print(list.sumEvery(4)); // [10, 26]

You can also customize the n from the method to sum for any other n.

  • Related