是否可以对具有重复字符的字符串进行排列?

时间:2019-09-07 08:03:52

标签: flutter dart permutation

我目前在flutter上使用trotter dart包,但是无法生成具有重复数字的字符串的所有排列。

它可以在1234上正常工作,但不能在2344上工作。

1 个答案:

答案 0 :(得分:0)

(免责声明:我是trotter的作者。感谢您对我的图书馆的关注!)

在处理数量适中的项目时,我们可以简单地创建从索引的规则排列序列到任意列表中各个项目的映射。

在这种情况下,任意列表包含字符串'2344'中的项目,因此我们可以如下生成这些项目的排列。 (但是请注意,对于无法区分的项目,排列不是唯一的。不过,可以通过转换为Set来摆脱非唯一项目。)

import 'package:trotter/trotter.dart';

main() {
  final items = characters('2344'),
      indices = List<int>.generate(items.length, (i) => i),
      permsOfItems = indices
          .permutations()
          .iterable
          .map((perm) => perm.map((index) => items[index]).join());

  print('All permutations (including non unique):');
  for (final perm in permsOfItems) {
    print(perm);
  }

  print('\nOnly unique:');
  for (final perm in permsOfItems.toSet()) {
    print(perm);
  }
}

输出:

All permutations (including non unique):
2344
2344
2434
4234
4243
2443
2443
2434
4234
4243
4423
4423
4432
4432
4342
4324
3424
3442
3442
4342
4324
3424
3244
3244

Only unique:
2344
2434
4234
4243
2443
4423
4432
4342
4324
3424
3442
3244