我不确定以前是否有人问过这个问题,因为我无法很快想出如何解释这个问题,所以如果有人问过,请指出正确的方向。
所以我想知道如何在 Java 中创建一个函数来创建列表列表。在这些列表中,我想要数字 0-5 的所有可能性,但每个列表中只有 4 个数字。我以一种简单的方式完成了这项工作,我可以在其中硬编码 4,但我不想硬编码该数字。
这是我用 Dart 编写的。
void generateLists() {
// possibles holds all the possible options. (1296 options in this case)
List<List<int>> possibles = new List();
int size = 4; // This should be the size of each list. This is what I'm asking about.
int maxNum = 6; // The numbers should go from 0 - maxNum.
// A terrible amount of for loops within each other to generate these lists.
for(int i=0; i<maxNum; i++) {
for(int j=0; j<maxNum; j++) {
for(int k=0; k<maxNum; k++) {
for(int l=0; l<maxNum; l++) {
// Create each list and add it to the possibles.
List<int> list = new List();
list.add(i);
list.add(j);
list.add(k);
list.add(l);
possibles.add(list);
}
}
}
}
// Print all the numbers to show it works.
for(List<int> l in possibles) {
print(l);
}
}
谢谢。
最佳答案
与 Iterable.expand :
main() {
int size = 4;
int maxNum = 6;
// create a list of nums [0,1,2,3]
final nums = new List.generate(maxNum, (i) => i);
// init result with a list of nums [[0],[1],[2],[3]]
Iterable<List> result = nums.map((i) => [i]);
for (int i = 1; i < size; i++) {
// every step adds a new element to the result
// [[0],[1],...] becomes [[0,0],[0,1],[1,0],[1,1],...]
result = result.expand((e) => nums.map((n) => e.toList()..add(n)));
}
result.forEach(print);
}
关于java - 如何制作包含 x-z 数字的 n 个数字的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631345/