dart - Dart 语言中的笛卡尔积

标签 dart cartesian

如何用 Dart 语言创建动态数量列表的笛卡尔积?

例如我有两个列表: X:[A,B,C]; Y:[W,X,Y,Z]

我想创建这样的列表[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]

虽然Python、Java有预实现的库,但我认为Dart语言没有。

最佳答案

使用 Dart 2.5.0 进行测试:

class PermutationAlgorithmStrings {
  final List<List<String>> elements;

  PermutationAlgorithmStrings(this.elements);

  List<List<String>> permutations() {
    List<List<String>> perms = [];
    generatePermutations(elements, perms, 0, []);
    return perms;
  }

  void generatePermutations(List<List<String>> lists, List<List<String>> result, int depth, List<String> current) {
    if (depth == lists.length) {
      result.add(current);
      return;
    }

    for (int i = 0; i < lists[depth].length; i++) {
      generatePermutations(lists, result, depth + 1, [...current, lists[depth][i]]);
    }
  }
}

您可以输入任意长度的字符串数组。 像这样使用:

  PermutationAlgorithmStrings algo = PermutationAlgorithmStrings([
                      ["A", "B", "C"],
                      ["W", "X", "Y", "Z"],
                      ["M", "N"]
                    ]);

输出:

output: [[A, W, M], [A, W, N], [A, X, M], [A, X, N], [A, Y, M], [A, Y, N], [A, Z, M], [A, Z, N], [B, W, M], [B, W, N], [B, X, M], [B, X, N], [B, Y, M], [B, Y, N], [B, Z, M], [B, Z, N], [C, W, M], [C, W, N], [C, X, M], [C, X, N], [C, Y, M], [C, Y, N], [C, Z, M], [C, Z, N]]

关于dart - Dart 语言中的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754481/

相关文章:

flutter - flutter中的数据转换

html - 具有笛卡尔坐标系的简单可缩放 SVG 图形

sql - 同一张表上的 DB 笛卡尔积

flutter - Dart/Flutter 中的 Spotify PKCE : "code_verifier was incorrect"

shared-libraries - Dart:Web 应用程序的库和导出

Flutter VsCode 错误 : You don't have an extension for debugging YAML

dart - Dart 式铸件

math - 围绕网格旋转矩形来计算玩家 View

grid - 算法[最好是fortran]从二维非结构化网格中插入数据以形成笛卡尔网格