英文:
how is the logic of neighbor values in to sub lists from integer list
问题
输入 =>
List integerList =[1,2,3,4,30,31,50,51,100];
期望输出 =>
List subLists =[[1,2,3,4],[30,31],[50,51],[100]];
基本标准,子组中间值的相邻差值应小于10
英文:
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
答案1
得分: 1
这个函数返回你想要的内容:
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) {///根据你的数字之间的差值标准,可以将此处的1更改为任何数字
groupedList.last.add(integerList[0]);
integerList.removeAt(0);
}
}
return groupedList;
}
英文:
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;
}
答案2
得分: -2
以下是翻译好的部分:
旧答案:
这是一个示例(假设按数字长度分组):
```dart
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); // 输出:[[1, 2, 3, 4], [50, 51], [100]]
}
编辑后的新答案:
我认为这可以满足您的需求:
```dart
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]]
英文:
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]]
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论