ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Theory of combinatorial algorithms

The headers of include/ADS/combinatorial go beyond the book, after volume 4A of The Art of Computer Programming of Knuth: the broadword computation of his section 7.1.3, which works on the 64 bits of a word as on a vector of bits, and the generation of the basic combinatorial objects of his section 7.2.1 (the tuples, the permutations, the combinations, the partitions and the strings of parentheses), each in two versions, one as the text describes it and one engineered for speed. The enumeration by backtrack of chapter 16 of the book is instead in include/ADS/backtrack. This page collects what the headers take for granted: the definitions and the notation (see Definitions and notation), the identities on which the broadword tricks rest (see Broadword computation), the population count of arrays (see Population counts of arrays), and the orders of the generation with the arguments behind their costs (see Generation of combinatorial objects). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the source that it follows.

Definitions and notation

A word \( x \) is an unsigned integer of 64 bits \( x = \sum_{k=0}^{63} x_k 2^k \), the bit \( x_k \) in the place \( k \), and the arithmetic on words is modulo \( 2^{64} \), so that \( -x = \lnot x + 1 \) (the complement plus 1). A word is also the set \( \{ k : x_k = 1 \} \subseteq \{ 0 , \ldots , 63 \} \), and the operations on the bits are those on the sets: \( \& \) the intersection, \( \mid \) the union, \( \oplus \) the symmetric difference.

The symbols of the headers of the area
SymbolMeaning
\( \& \), \( \mid \), \( \oplus \), \( \lnot \)the and, the or, the exclusive or and the complement of the bits, place by place
\( x \gg s \), \( x \ll s \)the shifts by \( s \) places, i.e., \( \lfloor x / 2^s \rfloor \) and \( 2^s x \bmod 2^{64} \)
\( \nu( x ) \)the sideways sum, the number of 1 bits of \( x \) (sidewaysSum())
\( \rho( x ) \), \( \lambda( x ) \)the ruler function, the place of the lowest 1 (the trailing zeros), and the place of the highest 1, \( \lfloor \log_2 x \rfloor \), of \( x \ne 0 \)
\( \mathtt{0x5555 \ldots 55} \)a constant in hexadecimal with its byte repeated in the 8 bytes of the word
\( \binom{n}{t} \), \( p( n ) \), \( \varpi_n \), \( C_n \)the binomial coefficient, the partitions of the integer \( n \), the Bell number (the partitions of a set of \( n \)) and the Catalan number \( \binom{2 n}{n} / ( n + 1 ) \)

Broadword computation

The tricks of Bitwise.h replace a loop over the bits by a few operations on the whole word, each of which acts on all the places at once. Four identities are at their base. The lowest 1 of \( x \ne 0 \) is in the place \( \rho( x ) \), and \( x - 1 \) has the same bits above it, a 0 in it and 1s below it; hence

\[ x \,\&\, -x = 2^{\rho( x )} , \quad x \mid ( x - 1 ) = x + 2^{\rho( x )} - 1 , \quad x \oplus ( x - 1 ) = 2^{\rho( x ) + 1} - 1 , \tag{1} \]

i.e., the lowest 1 alone (rightmostOne()), the 0s below it set (smearRight()), and a run of \( \rho( x ) + 1 \) ones, whose sideways sum gives ruler().

The sideways sum adds the bits in parallel: \( x - ( ( x \gg 1 ) \,\&\, \mathtt{0x5555 \ldots 55} ) \) holds in each field of 2 bits the number of its 1 bits (\( 2 a + b - a = a + b \)), two masked shifts add the fields in pairs into fields of 4 and then of 8 bits, and the product by \( \mathtt{0x0101 \ldots 01} \) sums the 8 bytes into the top one, no sum exceeding 64 and hence no carry crossing a byte. The same doubling gives lambda() by halving the width of the search, reverseBits() by swapping the fields of 1, 2, 4, 8 and 16 bits and the two halves, and interleave(), whose spread of 32 bits to the even places moves blocks of 16, 8, 4, 2 and 1 bits; each of them costs \( O( \log w ) \) operations for a word of \( w \) bits.

The Gray code \( g = x \oplus ( x \gg 1 ) \) of gray() changes by one bit from \( x \) to \( x + 1 \), since the carry flips the run of the lowest 1s of \( x \) and the bit above it, and the shift cancels all but one of the flips; its inverse is the prefix exclusive or \( x_k = \bigoplus_{j \ge k} g_j \), which grayInverse() computes by doubling the span, \( g \gets g \oplus ( g \gg s ) \) for \( s = 1 , 2 , 4 , \ldots , 32 \).

Lemma 1 (the trick of Gosper). For \( x \ne 0 \), with \( u = x \,\&\, -x \) and \( v = x + u \), the next larger word with as many 1 bits as \( x \) is

\[ v + ( ( ( v \oplus x ) / u ) \gg 2 ) . \tag{2} \]

Indeed, let the lowest run of 1s of \( x \) have \( r \) bits, from the place \( \rho( x ) \) up. The next word with as many 1s moves the top bit of that run one place up and the other \( r - 1 \) bits of the run to the bottom; \( v \) is \( x \) with the run cleared and the bit above it set, and \( v \oplus x \) is a run of \( r + 1 \) ones from the place \( \rho( x ) \), which the division by \( u \) brings to the place 0 and the shift by 2 shortens to \( r - 1 \) ones. nextCombination() of FastGeneration.h computes the same word without the division, from \( u = x \mid ( x - 1 ) \) and the shift by \( \rho( x ) + 1 \), the trailing zeros given by one instruction of the processor. Finally, the test of a zero byte of hasZeroByte() subtracts 1 from each byte: only a byte that is 0 borrows into its own top bit while having it clear in \( x \), and the lowest such byte is found exactly; a borrow from it may propagate a false 1 into a higher byte, which does not change the answer, since a zero byte exists in that case anyway.

Population counts of arrays

The 1 bits of an array of \( n \) words are the sum of their sideways sums, \( n \) instructions of population count on a processor that has one; popcount() of FastBitwise.h keeps four independent sums, so that the additions of consecutive words do not wait for one another. On the vectors of the processor, through the kernel of Google Highway that runs the best set of instructions found when the program starts, the method of Harley and Seal does fewer counts than words. A carry-save adder takes three vectors of bits \( a \), \( b \), \( c \) and gives, place by place,

\[ \mathrm{sum} = a \oplus b \oplus c , \quad \mathrm{carry} = \mathrm{maj}( a , b , c ) , \quad a + b + c = \mathrm{sum} + 2 \, \mathrm{carry} , \tag{3} \]

so that a tree of 15 adders reduces a block of 16 vectors and the accumulators of the ones \( o \), of the twos \( t \), of the fours \( f \) and of the eights \( e \) to new accumulators and a vector \( s \) of the sixteens, by (3) with the weights of each level. Only the vector of the sixteens is counted, and the accumulators once at the end: the total is \( 16 \sum \nu( s ) \) over the blocks plus \( 8 \nu( e ) + 4 \nu( f ) + 2 \nu( t ) + \nu( o ) \), at the cost of one count and of 15 carry-save adders, i.e., a few dozen logical operations, per block of 16 vectors. A vector is counted by the count of the lanes of Highway, one instruction where the processor has it, and otherwise the counts of its 16 nibbles looked up in a shuffle of bytes and the bytes of each word added. The rank of a bit, the population count of a prefix, is the base of select(), which finds the byte of the 1 of rank \( r \) by comparing \( r \) with the 8 prefix sums of the bytes in parallel, as in the zero-byte test, and then the bit inside the byte.

Generation of combinatorial objects

A generator visits all the objects of a kind in a fixed order, each once, and its cost is measured per object, i.e., amortized over the whole sequence; a loopless one also bounds the work between two consecutive objects by a constant. The orders of Generation.h and of FastGeneration.h are the following.

The objects, their number and their order
ObjectsNumberFunctionsOrder
\( n \)-tuples with \( 0 \le a_j < m_j \)\( \prod_j m_j \)mixedRadix(), grayTuples()lexicographic; reflected Gray, one place changed by 1
permutations of a multiset\( n! / \prod_v m_v! \)permutationsLex(), forEachPermutationLex()lexicographic
permutations of \( n \) items\( n! \)plainChanges(), heapPermutations(), forEachPermutation()one adjacent swap; one swap
\( t \)-combinations of \( n \)\( \binom{n}{t} \)combinationsLex(), forEachCombination(), forEachCombinationMask(), revolvingDoor()lexicographic; increasing as words; one item in and one out
partitions of \( n \)\( p( n ) \)integerPartitions()reverse lexicographic
partitions of a set of \( n \)\( \varpi_n \)setPartitions()lexicographic on the restricted growth strings
strings of \( n \) pairs of parentheses\( C_n \)nestedParentheses()lexicographic

The lexicographic successor has one scheme: find the last place that can grow, make it grow by the least amount, and set the places after it to their least values. For a permutation (Algorithm L of Narayana Pandita) the places after the last ascent \( a_j < a_{j+1} \) are nonincreasing, the least larger item of the suffix goes to the place \( j \), and the suffix is reversed. The scan of a suffix of length \( k \) happens once every \( k! \) permutations of distinct items; hence the work per permutation is at most proportional to \( \sum_{k \ge 1} k / k! = e \), a constant on the average though \( \Theta( n ) \) in the worst case. The same argument gives \( O( 1 ) \) amortized for the tuples, where a carry over the last \( k \) places happens once every \( m_{n-1} m_{n-2} \cdots m_{n-k} \ge 2^k \) tuples, and for the combinations. For the tuples the bound needs \( m_j \ge 2 \): a place of radix 1 holds 0 for ever, and a carry that walked over it would cost \( \Theta( n ) \) for each of the 2 tuples of \( m = ( 2 , 1 , \ldots , 1 ) \); mixedRadix() links each place to the last place of radix larger than 1 before it, so that the carries skip the places of radix 1 and the argument holds on the others. A generator also passes its own vector to the visit, never a copy, which would cost \( \Theta( n ) \) per object and hide the bound: plainChanges() keeps its permutation from the index 0 and the counters and the directions of Algorithm P from 1. The engineered versions of FastGeneration.h remove the constant itself from the inner loop: the last place of a combination runs through its values by a loop of its own, the last 3 items of a permutation are written in their 6 orders directly, and the words of forEachCombinationMask() move their lowest 1 up by one addition while it can, (2) being needed only once per run.

Lemma 2 (Heap's method). The iterative method of Heap, with a counter \( c_i < i \) for each place \( i \ge 1 \), swaps \( a_i \) with \( a_{c_i} \) if \( i \) is odd and with \( a_0 \) if it is even, and visits the \( n! \) arrangements, each once, with one swap between two of them.

Indeed, the counters run as a mixed-radix number with the radices \( 2 , 3 , \ldots , n \), i.e., through \( n! \) values, and Heap's choice of the swaps is the one that brings to the place \( i \) each of the items \( a_0 , \ldots , a_i \) once while the places below it run through all their arrangements. The place \( i \) changes once every \( i! \) arrangements, after the places below it have been reset; hence the work per arrangement of the counters is \( \sum_{i \ge 1} 1 / i! = e - 1 \), and unrolling the first 3 places, whose 6 arrangements are reached by the fixed swaps of the places 01, 02, 01, 02, 01 (forEachPermutation()), leaves the counters a step every 6 arrangements.

The orders with one change between consecutive objects come from reflections. In the reflected Gray order of the tuples the last place runs up and down, and each other place changes when all the places after it are at an end of their range; Algorithm H keeps for each place its direction and a focus pointer to the next place to change, and so it is loopless. The plain changes of Steinhaus, Johnson and Trotter (Algorithm P) move the largest item from one end to the other through the arrangements of the others, recursively, with one adjacent swap per step. The revolving door of the combinations is the order \( R( n , t ) \) defined by

\[ R( n , t ) = R( n - 1 , t ) , \; R( n - 1 , t - 1 )^{\mathrm{rev}} \cup \{ n - 1 \} , \tag{4} \]

with \( R( n , 0 ) \) and \( R( t , t ) \) of one object; the last object of \( R( n - 1 , t ) \) and the first of the reversed second part differ by the item \( n - 1 \) in and one item out, and revolvingDoor() follows (4) recursively. Finally, the partitions of a set are in bijection with their restricted growth strings, \( a_j \) the block of the item \( j \), the blocks numbered in the order of their least items, so that \( a_0 = 0 \) and \( a_j \le 1 + \max( a_0 , \ldots , a_{j-1} ) \), whose lexicographic successor (setPartitions()) scans fewer than 2 places per string on the average, since the strings whose last \( r \) places open new blocks are \( \varpi_{n-r} \le 2^{-r} \varpi_n \) for \( r \le n - 1 \) (since \( \varpi_k \ge 2 \varpi_{k-1} \) for \( k \ge 2 \)); and the strings of balanced parentheses, the words with as many opening as closing parentheses and no prefix with more closing than opening ones, are in bijection with the forests and with the binary trees of \( n \) nodes, which nestedParentheses() builds by a backtrack that tries the opening parenthesis first, a node of its tree costing \( O( 1 ) \) and every leaf of it being a solution.

Lemma 3 (the partitions of an integer, Algorithm 7.2.1.4P). integerPartitions() visits the \( p( n ) \) partitions of \( n \) in reverse lexicographic order writing fewer than \( 3 p( n ) \) parts in all, i.e., in \( O( 1 ) \) amortized time per partition.

Indeed, let \( a_q \) be the last part larger than 1. If \( a_q = 2 \), the successor replaces it by \( 1 + 1 \), writing two parts. Otherwise \( a_q \ge 3 \) drops to \( x = a_q - 1 \ge 2 \), the 1s after it are cut off at once by the length of the partition, and their sum plus 1 is written as parts \( x \) followed by one last part; this is the least partition after the current one in reverse lexicographic order, since the prefix before \( a_q \) cannot change and the rest is the largest partition with parts at most \( x \). Let \( \Phi \) be the number of parts larger than 1: the first case lowers \( \Phi \) by 1, and the second raises it by the parts \( x \) written plus at most 1 for the last part, the cut 1s and the part \( a_q \), still larger than 1, leaving it as it was. Since \( \Phi \) goes from 1, the partition \( ( n ) \), to 0, the partition \( 1^n \), the parts \( x \) written over the run are at most the number of the first cases, below \( p( n ) \), and each step writes besides them at most two parts. The former loop, which removed the 1s one at a time, wrote and erased \( \Theta( \sqrt{n} ) \) parts per partition on the average, the expected number of 1s in a partition of \( n \).

References

See also
D. E. Knuth, The Art of Computer Programming, vol. 4A, Addison-Wesley, 2011, sections 7.1.3 and 7.2.1
H. S. Warren, Hacker's Delight, 2nd ed., Addison-Wesley, 2012
M. Beeler, R. W. Gosper, R. Schroeppel, HAKMEM, MIT AI Memo 239, 1972, item 175 (the next word with as many 1 bits)
F. Gray, Pulse code communication, U.S. Patent 2,632,058, 1953
W. Mula, N. Kurz, D. Lemire, Faster population counts using AVX2 instructions, The Computer Journal 61(1), 111-120, 2018, doi:10.1093/comjnl/bxx046
S. Vigna, Broadword implementation of rank/select queries, WEA 2008, LNCS 5038, 154-168, doi:10.1007/978-3-540-68552-4_12
B. R. Heap, Permutations by interchanges, The Computer Journal 6(3), 293-298, 1963, doi:10.1093/comjnl/6.3.293
R. Sedgewick, Permutation generation methods, ACM Computing Surveys 9(2), 137-164, 1977, doi:10.1145/356689.356692
H. F. Trotter, Algorithm 115: Perm, Communications of the ACM 5(8), 434-435, 1962, doi:10.1145/368637.368660
S. M. Johnson, Generation of permutations by adjacent transposition, Mathematics of Computation 17(83), 282-285, 1963, doi:10.1090/S0025-5718-1963-0159764-2