skip to Main Content

input =>

List integerList =[1,2,3,4,30,31,50,51,100];

expecting output =>

List subLists =[[1,2,3,4],[30,31],[50,51],[100]];

basic criteria, subtraction result of each in between values of subgroups should be less than 10

2

Answers


  1. OLD ANSWER

    Here’s an example (assuming grouping by number length):

    import 'package:collection/collection.dart';
    
    void main() {
      List integerList =[1,2,3,4,50,51,100];
      final result = integerList
          .groupListsBy((element) => element.toString().length)
          .values
          .toList();
    
      print(result); // prints: [[1, 2, 3, 4], [50, 51], [100]]
    }
    

    EDIT:

    NEW ANSWER

    I believe this could do what you like:

      List integerList = [1,2,3,4,8,30,31,50,51,100];
      final result = integerList.fold<List<List<int>>>(
          [[]],
          (previousValue, element) => previousValue.last.isEmpty ||
                  (previousValue.last.last - element).abs() < 10
              ? [
                  ...previousValue.take(previousValue.length - 1),
                  [...previousValue.last, element]
                ]
              : [
                  ...previousValue,
                  [element]
                ]);
    
      print(result); // [[1, 2, 3, 4, 8], [30, 31], [50, 51], [100]]
    
    Login or Signup to reply.
  2. This function return what you want:

    List getGroupedList(List<int> integerList) {
        List<List<int>> groupedList = [];
        while (integerList.isNotEmpty) {
          groupedList.add([integerList.first]);
          integerList.removeAt(0);
          while (integerList.isNotEmpty&&integerList.first - groupedList.last.last == 1) {///YOU CAN ALTER THIS 1 TO ANY NUMBER ACCORDING TO YOUR CRITERIA OF DIFFERENCE BETWEEN NUMBERS
            groupedList.last.add(integerList[0]);
            integerList.removeAt(0);
          }
        }
        return groupedList;
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search