5

I need the classic N choose K algorithm to generate all the possible combinations of a list or iterable in Dart. Is there any implementation out there?

Cristian Garcia
  • 9,630
  • 6
  • 54
  • 75

2 Answers2

7

The package trotter seems to do what you are looking for.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

There is now an unreleased null safety version of trotter. Add the following dependency to your pubspec.yaml:

trotter: ^2.0.0-dev.1

Then you can do something like this:

var c = Combinations(3, characters('abcd'));
print('There are ${c.length} 3-combinations of the objects');
print('in ${c.items}.');
print('The first combination is ${c[0]}.');

You can make a Combinations object for a custom type as well:

var c = Combinations<MyType>(3, [obj1, obj2]);
Mike Knapp
  • 71
  • 4