0

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]
ASMA
  • 59
  • 1
  • 5

2 Answers2

1

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]
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • for every sublist I have to convert its value to float like this : double asFloat = ByteData.view(Uint8List.fromList(List.from(event)).buffer) .getFloat32(0, Endian.little); how can I modify your code. I mean the mart of final results ? – ASMA Jan 03 '23 at 14:41
  • I think you just need to replace the dataType, replace `int` with doouble – Md. Yeasin Sheikh Jan 03 '23 at 14:42
  • yeasin Actually the data entered is the first list is not created by me. I retrieved it from another device. So Ihave to use this method to convert every 4 ints to double like this :ByteData.view(Uint8List.fromList(List.from(event)).buffer) .getFloat32(0, Endian.little) – ASMA Jan 03 '23 at 14:44
  • are you getting list of double ? – Md. Yeasin Sheikh Jan 03 '23 at 14:48
  • I got list of ints and I have to converts every 4 ints to double – ASMA Jan 03 '23 at 14:49
  • you can do `final doubleList = intList.map((e) => e.toDouble()).toList();` – Md. Yeasin Sheikh Jan 03 '23 at 14:51
0

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.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35