Perm

A struct that generates all possible permutations of a sequence.

Notes:

Permutations are output in undefined order.

The array returned by front is recycled across iterations. To preserve it across iterations, wrap this range using map!"a.dup" or map!"a.idup".

Constructors

this
this(U input)

Generate permutations from an input range. * Create a duplicate of this sequence * so that the original sequence is not modified.

Members

Functions

popFront
void popFront()

Get the next permutation in the sequence. This will overwrite the contents of the array returned by the last call to front.

Properties

empty
bool empty [@property getter]
front
const(T)[] front [@property getter]

Returns the current permutation. The array is const because it is recycled across iterations and modifying it would destroy the state of the permutation generator.

length
size_t length [@property getter]

The number of permutations left.

save
typeof(this) save [@property getter]

Bugs

Only supports iterating over up to size_t.max permutations. This means the max permutation length is 12 on 32-bit machines, or 20 on 64-bit. This was a conscious tradeoff to allow this range to have a length of type size_t, since iterating over such huge permutation spaces would be insanely slow anyhow.

Examples

1 double[][] res;
2 auto perm = map!"a.dup"(Perm!(double)([1.0, 2.0, 3.0][]));
3 foreach(p; perm) {
4      res ~= p;
5 }
6 
7 auto sorted = sort(res);
8 assert(sorted.canFind([1.0, 2.0, 3.0]));
9 assert(sorted.canFind([1.0, 3.0, 2.0]));
10 assert(sorted.canFind([2.0, 1.0, 3.0]));
11 assert(sorted.canFind([2.0, 3.0, 1.0]));
12 assert(sorted.canFind([3.0, 1.0, 2.0]));
13 assert(sorted.canFind([3.0, 2.0, 1.0]));
14 assert(sorted.length == 6);

Meta