flutter 从整数列表到子列表中的邻居值的逻辑如何[已关闭]

nc1teljy  于 2023-01-09  发布在  Flutter
关注(0)|答案(2)|浏览(120)

4小时前关门了。
这篇文章是编辑和提交审查2小时前。
Improve this question
输入=〉

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

预期输出=〉

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

基本标准,各亚组值之间的减法结果应小于10

hjqgdpho

hjqgdpho1#

此函数返回所需内容:

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;
  }
lndjwyie

lndjwyie2#

旧答案
下面是一个示例(假设按数字长度分组):

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]]
}

编辑:
新答案
我相信这可以做你喜欢的:

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]]

相关问题