java - 如何制作包含 x-z 数字的 n 个数字的列表

标签 java list for-loop dart

我不确定以前是否有人问过这个问题,因为我无法很快想出如何解释这个问题,所以如果有人问过,请指出正确的方向。

所以我想知道如何在 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/

相关文章:

java - 如何将 XDDF 图表添加到特定段落运行(即表格中的单元格)?兴趣点4.0.1

Python 字典排序列表,部分标签可能缺失

java - 如何从java中的html标签中删除属性

java - 在另一个 Activity 中使用从主 Activity 实例化的套接字

python - 如何返回一个由Python中另一个列表中提取的元素组成的列表?

java - 非法参数异常 : Could not parse [/24] - SubnetUtils

r - 如何将值存储在R中for循环内的向量中

java - int low 和 int high 之间的数字之和; java

php - 如何在php的矩阵表中显示数组

Java Mysql大数据超出堆空间