Home > Mobile >  what is the logic of neighbor values in to sub lists from integer list
what is the logic of neighbor values in to sub lists from integer list

Time:01-10

input =>

 List integerList=[1,2,4,11,14,15,16,16,19,30,31,50,51,100,101,105];

expecting output =>

 List sub = [[1,2,4],[11,14,15,16,16,19],[30,31],[50,51],[100,101,105]];

1,2,4 7 difference to 11,14,15,16,16,19 11 difference to 30,31, 19 difference to 50,51, 49 difference to 100,101,105

 basic crietirea , atleast 7 difference with the values at the time of separation of
 integerlist.

CodePudding user response:

List integerList=[1,2,4,11,14,15,16,16,19,30,31,50,51,100,101,105]; //input
//input should orderd, just sort your input otherwise you will not get expected output

var subList=integerList.splitBetween((v1, v2) => (v2 - v1).abs() > 9);
print(subList);
//you should minus 1 from your criteria, here 10 goes to 9. or change it to:(v2 - v1).abs() >= 10

thanks, https://stackoverflow.com/users/2252830/pskink he is the author

CodePudding user response:

List integerList = [1,2,3,4,8,30,31,50,51,100];. //input should be sorted
  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]]

Source from this link https://stackoverflow.com/a/75054991/17971818 Thanks Ivo https://stackoverflow.com/users/1514861/ivo

  • Related