问题
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