|
ADS
Algorithms and Data Structures
|
The engineered generation of permutations and combinations, beyond the book [see Generation.h for the algorithms of Knuth (section 7.2.1 of The Art of Computer Programming) as written there]: the same objects, with the work per object brought down to a few instructions, so that visit() is the larger part of the time. More...
#include "ADS/Contract.h"#include "ADS/combinatorial/Bitwise.h"#include "ADS/combinatorial/Generation.h"#include <algorithm>#include <bit>#include <cstdint>#include <type_traits>#include <utility>#include <vector>#include "ADS/combinatorial/impl/FastGeneration.tpp"Go to the source code of this file.
Namespaces | |
| namespace | ADS |
Functions | |
| template<class T, class F> | |
| long | ADS::forEachPermutation (std::vector< T > &a, F &&visit) |
| the \( n! \) arrangements of \( a \) by Heap's method, visit( a ) on each | |
| template<class T, class F> | |
| long | ADS::forEachPermutationLex (std::vector< T > &a, F &&visit) |
| the distinct permutations of the multiset \( a \) in lexicographic order from \( a \) sorted, visit( a ) on each; \( a \) ends sorted | |
| template<class F> | |
| long | ADS::forEachCombination (int n, int t, F &&visit) |
| the increasing \( t \)-tuples of \( [ 0 , n ) \) in lexicographic order, visit( c ) on each, \( c \) a const std::vector< int > of size \( t \) | |
| constexpr Word | ADS::nextCombination (Word x) |
| the next larger word with as many 1 bits as \( x \) | |
| template<class F> | |
| long | ADS::forEachCombinationMask (int n, int t, F &&visit) |
| the words of \( t \) 1 bits below \( 2^n \) in increasing order, visit( x ) on each | |
The engineered generation of permutations and combinations, beyond the book [see Generation.h for the algorithms of Knuth (section 7.2.1 of The Art of Computer Programming) as written there]: the same objects, with the work per object brought down to a few instructions, so that visit() is the larger part of the time.
Each function calls visit() on every object and returns their number; if visit() returns bool, true stops the generation, and if it returns void there is no test at all.
\[ u = x \mid ( x - 1 ) , \quad x' = ( u + 1 ) \mid \big( ( ( \lnot u \,\&\, ( u + 1 ) ) - 1 ) \gg ( \rho( x ) + 1 ) \big) , \]
\( \rho \) the trailing zeros; while the lowest 1 of \( x \) has a 0 above it, below the place \( n - 1 \), the next word is \( x + ( x \,\&\, -x ) \), which a loop of its own does in two operations, so that the step above runs once per run of the lowest 1, i.e., for a fraction of about \( t / n \) of the words.The counts are \( n! \), the multinomial \( n! / \prod_v m_v! \) of the multiplicities and \( \binom{n}{t} \), as for Generation.h. The contracts [see Contract.h]: \( 0 \le t \le n \), \( n \le 64 \) for the words. The functions are defined in FastGeneration.tpp.