Is it possible to get permutations for a String that has repeated characters?

独自空忆成欢 提交于 2020-01-25 09:45:09

问题


I am currently using the trotter dart package on flutter, however it is unable to generate all permutations of strings with repeated numbers.

It works fine with 1234, but not with 2344.


回答1:


(Disclaimer: I'm the author of trotter. Thanks for your interest in my library!)

When dealing with a moderate number of items, we can simply create a mapping from a regular sequence of permutations of indices to respective items in an arbitrary list.

In this case, the arbitrary list contains the items in the string '2344', so we could generate the permutations of these items as follows. (Notice, however, with indistinguishable items, the permutations are not unique. We could get rid of non unique items by converting to a Set, though.)

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);
  }
}

Output:

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


来源:https://stackoverflow.com/questions/57831836/is-it-possible-to-get-permutations-for-a-string-that-has-repeated-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!