taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Volume C1 · Basic concepts · TAOCP Section 1.3.3

Applications to permutations

Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.

Read it next to Section 1.3.3 of the book. The nodes and the exercises of the section.

Contents
  1. Applications to permutations, cycle products and inverses in place

Applications to permutations, cycle products and inverses in place

Overview

Section 1.3.3 of TAOCP has two aims. It gives four programs for MIX that are longer than those of Section 1.3.2, and it uses them to teach the structure of a permutation. A permutation can be seen as a rearrangement of objects, and then it falls apart into disjoint cycles. The section writes down this notation, defines the product of two permutations, and builds two algorithms that multiply a list of cycles. Algorithm A works like a person: it scans the input again and again, once for each step of each output cycle. Algorithm B works like a machine: it scans the input once from right to left and keeps the whole current permutation in a table. Then the section shows two ways to replace a permutation of {1,…,n}\{1, \ldots, n\} by its inverse inside the same array, Algorithm I (by cycles, with signs as marks) and Algorithm J (by a chain of positive links). The programs are analysed along the way. The last part of the section turns to random permutations. It counts the cycles of a random permutation with the Stirling numbers of the first kind, and it counts the fixed points with derangement numbers and with the principle of inclusion and exclusion.

The section uses Section 1.2.5 for permutations, Section 1.2.6 for binomial coefficients and for the Stirling numbers, Section 1.2.7 for the harmonic numbers, Section 1.2.10 for the mean and the deviation of a count with a generating function, and Section 1.3.2 for MIX programs with frequency counts. C1 proves every statement of the section on its own, with examples that C1 made and ran, and it fixes the meaning of each count by running the MIX programs of this chapter on a MIX simulator. The listings themselves are not printed here. The reader has them in the book, and the chapter describes the structure of each program and the work of each group of lines.

The ideas

A permutation has two pictures, a table and a set of cycles. The table (two-line form) lists each object and its image. The cycle form follows an object to its image, to the image of the image, and so on until the chain returns. Each object lies on exactly one such closed chain. So a permutation is the same thing as a set of disjoint cycles. The cycle form is shorter, and it shows the structure: the lengths of the cycles, the fixed points, the order of the permutation.

The product of permutations means one after the other, read from left to right. The text writes π1π2\pi_1\pi_2 for the permutation that applies π1\pi_1 first. The product of a list of cycles is therefore found by following an object through the cycles from the left. The list does not have to be disjoint. The answer is a permutation, and the work of Algorithms A and B is to write the answer as disjoint cycles.

Algorithm A tags symbols. Algorithm B keeps a table. In Algorithm A, each symbol of the input formula that has been used is marked, and the algorithm builds each output cycle by repeated scans of the formula. In Algorithm B, the algorithm reads the formula from the right and keeps, for each name, its image under the part of the formula that it has read. The table needs one exchange for each symbol, plus a search for the name in a list when the names are not numbers. Algorithm A makes a pass over the whole formula for each name, while Algorithm B reads the formula once. This is why the two programs differ in time by a large factor.

A MIX analysis is a puzzle about counts. For each group of lines, name the number of executions. Kirchhoff's first law (flow in equals flow out) links the numbers. The remaining numbers have a meaning in the data, such as the number of cycles in the input. A few counts link in a way that only the structure of the problem shows, and one of them (the sum of the three scan steps) needs a special argument.

Inverting in place is a rewiring of cycles. To invert a permutation, point each arrow backwards. When the array may not grow, each cycle is rewired one entry at a time, and the algorithm needs a mark for the entries that it has already treated. Algorithm I marks with a minus sign. Algorithm J puts a minus sign on every entry first, and then it uses chains of positive entries as a stack of links. Algorithm I does a fixed amount of work per entry, and Algorithm J does work that grows like nln⁡nn \ln n on average.

Random permutations: cycles are left-to-right minima, and fixed points have the same statistics for all n≥2n \ge 2. If the cycles are written in a fixed canonical order, the parentheses can be dropped without loss, and the cycles become the left-to-right minima of a linear arrangement. This turns the number of cycles into a quantity that Section 1.2.10 has already studied. The number of fixed points is a different problem. The answer is the sum of terms (z−1)j/j!(z - 1)^j / j!, whose derivative is the same sum with one term less. This gives the mean 11 and the variance 11, for every n≥2n \ge 2.

C1 differs from the book in these points. It does not use the examples of the book: every example is new and was checked by a program. It proves the correctness of Algorithms A, B and J with explicit invariants, where the book leaves the proofs to the reader or to exercises. It derives the running time of Program B in full (the book leaves this to exercise 10), and it finds the average of the count AA of Algorithm J (the book leaves this to exercise 14), which shows the time nln⁡nn \ln n of Algorithm J.

Definitions, results and proofs

Definition (permutation, two-line form, cycle form, TAOCP Section 1.3.3). A permutation of a finite set SS is a bijection of SS to itself. The two-line form of a permutation π\pi writes the elements of SS in any order in the top row and, under each element xx, the image π(x)\pi(x). A cycle (x1 x2…xk)(x_1\, x_2 \ldots x_k) with distinct elements is the permutation that maps x1↦x2↦⋯↦xk↦x1x_1 \mapsto x_2 \mapsto \cdots \mapsto x_k \mapsto x_1 and fixes all other elements. The cycle form of π\pi is a list of cycles with pairwise disjoint sets of elements whose product is π\pi. The list leaves out the cycles with one element (the fixed points), and the empty list is written ()() and stands for the identity.

Node: 1.3.3-def-permutation · Lean: not yet stated

Explanation. A permutation can be read in two ways. As a rearrangement, the object xx moves to the place where π(x)\pi(x) stood. As a renaming, the object named xx gets the new name π(x)\pi(x). The two-line form does not depend on the order of the columns, so a permutation of nn objects has n!n! two-line forms. A cycle of one element is the identity on every element, which is why the cycle form can leave it out. The identity has no cycle of length 22 or more, and the symbol ()() marks this. The next result says that the cycle form always exists and that it is almost unique.

Example. Let μ\mu be the map x↦4x mod 9x \mapsto 4x \bmod 9 on S={0,1,…,8}S = \{0, 1, \ldots, 8\}. The images of 0,1,…,80, 1, \ldots, 8 are 0,4,8,3,7,2,6,1,50, 4, 8, 3, 7, 2, 6, 1, 5. They are distinct, so μ\mu is a permutation. Follow 11: 1→4→16 mod 9=7→28 mod 9=11 \to 4 \to 16 \bmod 9 = 7 \to 28 \bmod 9 = 1, a cycle (1 4 7)(1\,4\,7). Follow 22: 2→8→32 mod 9=5→20 mod 9=22 \to 8 \to 32 \bmod 9 = 5 \to 20 \bmod 9 = 2, a cycle (2 8 5)(2\,8\,5). The elements 00, 33 and 66 are fixed (12 mod 9=312 \bmod 9 = 3 and 24 mod 9=624 \bmod 9 = 6). So the cycle form is (1 4 7)(2 8 5)(1\,4\,7)(2\,8\,5). The two cycles of length 33 and the three fixed points use 3+3+3=93 + 3 + 3 = 9 elements, so no element is lost.

Proof of the existence and the uniqueness of the cycle form. Let π\pi be a permutation of a finite set SS and let x1∈Sx_1 \in S. Put xi+1=π(xi)x_{i+1} = \pi(x_i). Since SS is finite, some value repeats. Let xk+1x_{k+1} be the first value that equals an earlier one, say xk+1=xrx_{k+1} = x_r with r≤kr \le k. If r>1r > 1, then xk≠xr−1x_{k} \neq x_{r-1}, because x1,…,xkx_1, \ldots, x_k are distinct and r−1<kr - 1 < k and r−1≥1r - 1 \ge 1. But π(xr−1)=xr=π(xk)\pi(x_{r-1}) = x_r = \pi(x_k), which contradicts the injectivity of π\pi. So r=1r = 1, and (x1…xk)(x_1 \ldots x_k) is a cycle that agrees with π\pi on its elements. Call its element set the orbit of x1x_1. Two orbits are equal or disjoint: if they share an element, then the chain from that element is in both, and each chain contains the other starting point. Hence SS splits into disjoint orbits, and the product of the cycles of the orbits equals π\pi on each element. Dropping the orbits of size 11 gives the cycle form. For uniqueness, take any cycle form. Each cycle lists an orbit of π\pi, because the chain x↦π(x)↦⋯x \mapsto \pi(x) \mapsto \cdots stays in the cycle that contains xx. So each cycle of a cycle form is a rotation of the orbit cycle, and the orbit cycles are unique up to the order in which the cycles are written. The cycle form is thus unique up to the order of the cycles and the choice of the first element in each cycle. □\square

Example (a permutation of six letters in two-line form, TAOCP eq. 1.3.3(1)). The permutation ρ\rho of {a,b,c,d,e,f}\{a, b, c, d, e, f\} that sends a↦da \mapsto d, b↦cb \mapsto c, c↦ec \mapsto e, d↦fd \mapsto f, e↦be \mapsto b, f↦af \mapsto a has the two-line form

ρ=(abcdefdcefba).\rho = \begin{pmatrix} a & b & c & d & e & f \\ d & c & e & f & b & a \end{pmatrix}.

Node: 1.3.3-(1) · Lean: not yet stated

Explanation. Each column has an object above and its image below. Under the rearrangement reading, the object at place aa moves to place dd (first column). Under the renaming reading, the name aa becomes the name dd. The bottom row is a rearrangement of the top row, which is what makes ρ\rho a permutation: no two columns have the same image.

Example. The same permutation can be written with the columns in the reverse order:

(fedcbaabfecd).\begin{pmatrix} f & e & d & c & b & a \\ a & b & f & e & c & d \end{pmatrix}.

Each column is a column of the first table, so this is the same permutation. Altogether there are 6!=7206! = 720 two-line forms of ρ\rho, one for each order of the six columns.

Proof. The bottom row of the table above lists d,c,e,f,b,ad, c, e, f, b, a. These are the six letters, each once, so ρ\rho is a bijection, hence a permutation. A two-line form is a choice of an order for the columns. Two different orders give different strings, and each order gives a valid form, so the number of forms is 6!=7206! = 720. □\square

Example (the same permutation in cycle form, TAOCP eq. 1.3.3(2)). The permutation ρ\rho of eq. 1.3.3(1) is

(a d f)(b c e).(a\,d\,f)(b\,c\,e).

Node: 1.3.3-(2) · Lean: not yet stated

Explanation. Start at aa: a↦d↦f↦aa \mapsto d \mapsto f \mapsto a. This closes the cycle (a d f)(a\,d\,f). The letter bb is not yet used: b↦c↦e↦bb \mapsto c \mapsto e \mapsto b closes (b c e)(b\,c\,e). All six letters are used, so the list is complete. The cycle form shows that ρ\rho has two cycles of length 33 and no fixed point.

Example. A fixed point does not appear in the cycle form. Take the permutation σ\sigma with a↦da \mapsto d, d↦ad \mapsto a, b↦bb \mapsto b, c↦ec \mapsto e, e↦fe \mapsto f, f↦cf \mapsto c. Its cycle form is (a d)(c e f)(a\,d)(c\,e\,f). The letter bb is a fixed point and does not appear.

Proof. Apply the existence argument of the definition to ρ\rho with x1=ax_1 = a and then x1=bx_1 = b. It gives the two orbits {a,d,f}\{a, d, f\} and {b,c,e}\{b, c, e\}, and the cycles above. □\square

Example (other cycle forms of the same permutation, TAOCP eq. 1.3.3(3)). The permutation ρ\rho of eq. 1.3.3(2) can also be written (b c e)(a d f)(b\,c\,e)(a\,d\,f), (d f a)(c e b)(d\,f\,a)(c\,e\,b) and (f a d)(e b c)(f\,a\,d)(e\,b\,c). The string (a f d)(b c e)(a\,f\,d)(b\,c\,e) is a different permutation. In all, ρ\rho has 1818 cycle forms without fixed points.

Node: 1.3.3-(3) · Lean: not yet stated

Explanation. A cycle may start at any of its elements, and the cycles may come in any order, because disjoint cycles do not interact. A cycle may not be reversed: (a f d)(a\,f\,d) sends aa to ff, while ρ\rho sends aa to dd. The reverse of a cycle is its inverse.

Example. The string (a f d)(b c e)(a\,f\,d)(b\,c\,e) sends a↦fa \mapsto f, but ρ(a)=d\rho(a) = d, so the string is not ρ\rho. The count 1818 is 2!⋅3⋅32! \cdot 3 \cdot 3: two orders of the two cycles, three starting points for each cycle. A permutation with one cycle of length 44 and one of length 22 has 2!⋅4⋅2=162! \cdot 4 \cdot 2 = 16 cycle forms.

Proof of the count. Suppose that the cycle form of π\pi has kk cycles of lengths ℓ1,…,ℓk\ell_1, \ldots, \ell_k (all at least 22). A way to write π\pi is an order of the kk cycles and, for each cycle, a choice of a starting element. By the uniqueness part of the definition, each such choice gives a valid form, and different choices give different strings (the strings differ in the order of their first symbols or in a first symbol of a cycle, since the elements are distinct). The number of choices is k! ℓ1⋯ℓkk! \, \ell_1 \cdots \ell_k. For ρ\rho, k=2k = 2 and ℓ1=ℓ2=3\ell_1 = \ell_2 = 3, so the count is 2⋅3⋅3=182 \cdot 3 \cdot 3 = 18. □\square

Definition (the product of two permutations, TAOCP eq. 1.3.3(4)). Let π1\pi_1 and π2\pi_2 be permutations of the same set SS. The product π1π2\pi_1\pi_2 is the permutation that applies π1\pi_1 first and π2\pi_2 second:

(π1π2)(x)=π2(π1(x))(x∈S).(\pi_1\pi_2)(x) = \pi_2(\pi_1(x)) \qquad (x \in S).

Node: 1.3.3-(4) · Lean: not yet stated

Explanation. The product of permutations is the composition of the maps, written in the order in which the maps act. Two facts follow at once. The product is associative, so a product of many factors needs no parentheses. The product is not commutative. A reader who knows composition of functions will see that π1π2\pi_1\pi_2 here is the function π2∘π1\pi_2 \circ \pi_1. Many books on algebra use the other order, and so does Mathlib, where Equiv.Perm.mul_apply states (fg)(x)=f(g(x))(f g)(x) = f(g(x)). When C1 quotes a Lean result about products, C1 states the order.

Example. Let ρ\rho be as above and let τ=(a b c)\tau = (a\,b\,c), that is a↦b↦c↦aa \mapsto b \mapsto c \mapsto a with d,e,fd, e, f fixed. For ρτ\rho\tau (first ρ\rho, then τ\tau): a↦d↦da \mapsto d \mapsto d, b↦c↦ab \mapsto c \mapsto a, c↦e↦ec \mapsto e \mapsto e, d↦f↦fd \mapsto f \mapsto f, e↦b↦ce \mapsto b \mapsto c, f↦a↦bf \mapsto a \mapsto b. In two-line form

ρτ=(abcdefdaefcb).\rho\tau = \begin{pmatrix} a & b & c & d & e & f \\ d & a & e & f & c & b \end{pmatrix}.

For τρ\tau\rho (first τ\tau, then ρ\rho): a↦b↦ca \mapsto b \mapsto c, b↦c↦eb \mapsto c \mapsto e, c↦a↦dc \mapsto a \mapsto d, d↦d↦fd \mapsto d \mapsto f, e↦e↦be \mapsto e \mapsto b, f↦f↦af \mapsto f \mapsto a:

τρ=(abcdefcedfba).\tau\rho = \begin{pmatrix} a & b & c & d & e & f \\ c & e & d & f & b & a \end{pmatrix}.

The two products differ (aa goes to dd in one and to cc in the other).

Proof. The product is a bijection of SS, because a composition of bijections is a bijection. The product is associative: for three permutations, ((π1π2)π3)(x)=π3(π2(π1(x)))=(π1(π2π3))(x)((\pi_1\pi_2)\pi_3)(x) = \pi_3(\pi_2(\pi_1(x))) = (\pi_1(\pi_2\pi_3))(x). The identity map is a unit on both sides. The example shows two permutations with ρτ≠τρ\rho\tau \neq \tau\rho, so the product is not commutative in general. □\square

Example (a product of permutations in cycle form, TAOCP eq. 1.3.3(5)). With ρ=(a d f)(b c e)\rho = (a\,d\,f)(b\,c\,e), the product of ρ\rho and the permutation (a b)(d e)(a\,b)(d\,e) is

(a d f)(b c e)(a b)(d e)=(a e)(b c d f).(a\,d\,f)(b\,c\,e)(a\,b)(d\,e) = (a\,e)(b\,c\,d\,f).

Node: 1.3.3-(5) · Lean: not yet stated

Explanation. A cycle form is itself a product of permutations: the disjoint cycles (a d f)(a\,d\,f) and (b c e)(b\,c\,e) commute, and their product is ρ\rho. So a product of cycle forms is a longer list of cycles, and the notation does not need a multiplication sign. The list is not disjoint, because aa occurs in (a d f)(a\,d\,f) and in (a b)(a\,b). The answer is found by following each letter through the four factors from left to right.

Example. The trace of each letter, with one column for each factor, is

Letter after (a d f)(a\,d\,f) after (b c e)(b\,c\,e) after (a b)(a\,b) after (d e)(d\,e)
aa dd dd dd ee
bb bb cc cc cc
cc cc ee ee dd
dd ff ff ff ff
ee ee bb aa aa
ff aa aa bb bb

The last column is the product: a↦ea \mapsto e, b↦cb \mapsto c, c↦dc \mapsto d, d↦fd \mapsto f, e↦ae \mapsto a, f↦bf \mapsto b. The cycles are (a e)(a\,e) and (b c d f)(b\,c\,d\,f).

Proof. A product of rr factors maps xx to πr(⋯π2(π1(x)))\pi_r(\cdots\pi_2(\pi_1(x))) by the definition of eq. 1.3.3(4) and induction on rr. Each column of the table applies one factor to the entries of the column before. A cycle (x1…xk)(x_1 \ldots x_k) maps xi↦xi+1x_i \mapsto x_{i+1} for i<ki < k and xk↦x1x_k \mapsto x_1, and it fixes every letter outside. Row ee: (a d f)(a\,d\,f) fixes ee, (b c e)(b\,c\,e) maps e↦be \mapsto b, (a b)(a\,b) maps b↦ab \mapsto a, (d e)(d\,e) fixes aa. The other rows follow in the same way. The cycle form of the final column is then read by the proof of the definition: a→e→aa \to e \to a and b→c→d→f→bb \to c \to d \to f \to b. □\square

Example (the product that the programs compute, TAOCP eq. 1.3.3(6)). The input of Algorithms A and B is a formula, a list of cycles in which one letter may occur many times. For example, the formula

(a b c d)(b e)(c f a)(d e f)(a\,b\,c\,d)(b\,e)(c\,f\,a)(d\,e\,f)

has the value (a f)(b d c e)(a\,f)(b\,d\,c\,e). The programs of this section take such a formula and produce the disjoint cycle form of its value.

Node: 1.3.3-(6) · Lean: not yet stated

Explanation. The hand method follows one letter at a time through the factors and writes the answer cycle by cycle: find the image of the first unused letter, then the image of that image, and so on until the chain returns to the first letter. The method needs only the rule of the product, but it scans the whole formula once for each step of each output cycle. This is the method that Algorithm A turns into a program.

Example. The trail of each letter through the four factors is:

Letter start after (a b c d)(a\,b\,c\,d) after (b e)(b\,e) after (c f a)(c\,f\,a) after (d e f)(d\,e\,f)
aa aa bb ee ee ff
bb bb cc cc ff dd
cc cc dd dd dd ee
dd dd aa aa cc cc
ee ee ee bb bb bb
ff ff ff ff aa aa

So a↦f↦aa \mapsto f \mapsto a, which is the cycle (a f)(a\,f), and b↦d↦c↦e↦bb \mapsto d \mapsto c \mapsto e \mapsto b, which is (b d c e)(b\,d\,c\,e).

Proof. The table is computed with the rule of the product, as in the example above. Check one row: aa goes to bb in (a b c d)(a\,b\,c\,d); bb goes to ee in (b e)(b\,e); ee is not in (c f a)(c\,f\,a); ee goes to ff in (d e f)(d\,e\,f). A permutation of six letters in which a↦f↦aa \mapsto f \mapsto a and b↦d↦c↦e↦bb \mapsto d \mapsto c \mapsto e \mapsto b has the cycle form (a f)(b d c e)(a\,f)(b\,d\,c\,e) by the definition of the cycle form. □\square

Algorithms and programs

Algorithm (multiplication of permutations in cycle form by repeated scans, TAOCP Algorithm 1.3.3A). Input: a formula, that is a list of cycles over names, where a name may occur in several cycles and in one cycle at most once. Output: the cycle form of the product of the formula, with fixed points left out. The algorithm tags the symbols that it has used, and it writes the output cycles one at a time. For each output element it makes one pass from left to right over the whole formula.

Node: Algorithm 1.3.3A · Lean: not yet stated

The idea. To find the image of a name xx under the formula, carry a value vv, start with v=xv = x, and read the cycles from left to right. In each cycle that contains vv, replace vv by the symbol that follows vv in the cycle (the first symbol of the cycle if vv is the last). At the end vv is the image of xx. The algorithm does this for the elements of an output cycle one after the other. It marks each symbol that it uses. A symbol that no pass has used yet is the start of an output cycle that has not been written. This works because each name is the start of a path through the formula, and the paths of different names do not share a symbol (the proof below).

The steps. In the steps, a closing copy is the symbol that replaces the closing parenthesis of a cycle. It has the name of the first symbol of the cycle.

A1. For each cycle, replace ")" by a closing copy of its first symbol.
    Mark every proper symbol (not "(", not a closing copy) as untagged.
    Set the output to empty.
A2. Find the leftmost untagged proper symbol. If none exists, go to A6.
    Else put START <- that name, append "(" and START to the output,
    tag that symbol, and set v <- the symbol that follows it.
    Set the pass position p to the cell after the one that holds v.
A3. Pass over the cells from p to the right end.
    For each cell c whose name equals v: tag c, set v <- the symbol in the cell
    that follows c, and continue after that cell.
A4. If v differs from START, append v to the output, set p <- first cell,
    and go to A3.
A5. Append ")" to the output. If the cycle just written has the form "(START)",
    delete it. Go to A2.
A6. Stop. The output is the answer. If it is empty, the answer is ().

A worked run. Let the formula be Φ=(a b c)(a b)(d e)\Phi = (a\,b\,c)(a\,b)(d\,e). After A1 the cells are (with ∗* for a closing copy) ( a b c a* ( a b a* ( d e d*. Thirteen cells are in use. By the numbering of eq. 1.3.3(19), X=1X = 1, Y=13Y = 13, M=3M = 3, N=5N = 5. The run is:

Step START Cells tagged in this step vv at the end of the pass Output after the step
A2, A3 aa cell of aa in cycle 1, then bb in cycle 2 aa (a
A5 v=v = START, so close; the cycle is (a)(a) and is deleted empty
A2, A3 bb bb in cycle 1 cc (b
A4, A3 cc in cycle 1, then aa in cycle 2 bb (b c
A5 close (b c)
A2, A3 dd dd in cycle 3 ee (b c)(d
A4, A3 ee in cycle 3 dd (b c)(d e
A5 close (b c)(d e)

Then A2 finds no untagged proper cell (the proper cells are a,b,c,a,b,d,ea, b, c, a, b, d, e and all seven are tagged), and the answer is (b c)(d e)(b\,c)(d\,e). Direct check with the rule of the product: in cycle 1, a↦ba \mapsto b, then in cycle 2, b↦ab \mapsto a, and cycle 3 fixes aa, so a↦aa \mapsto a. For bb: cycle 1 gives cc, and the later cycles fix cc, so b↦cb \mapsto c. For cc: cycle 1 gives aa, cycle 2 gives bb, cycle 3 fixes bb, so c↦bc \mapsto b. Only cycle 3 moves dd and ee, so they exchange. The answer matches. The algorithm made five passes, one for each of the five names.

Correctness. For a name yy, the path of yy is the sequence of cells that the value vv uses when vv starts as yy and the pass goes through the formula from the left. The pass tags each cell that matches vv and moves vv past it. Four facts prove the algorithm.

  1. A closing copy never matches vv in a pass. Let a cycle be (x1…xk)(x_1 \ldots x_k) and let ckc_k be its closing copy with the name x1x_1. A pass that has v=x1v = x_1 meets the cell of x1x_1 before ckc_k, matches it, and gets v=x2v = x_2 (or v=x1v = x_1 again only if k=1k = 1, and then the match skips ckc_k because it is the cell that follows). The names in a cycle are distinct, so no later cell of the cycle matches. If v≠x1v \ne x_1 on arrival, the closing copy does not match. In all cases the closing copy is only read as the symbol that follows xkx_k.
  2. The pass of xx gives v=v = the image of xx at the end. This follows from the rule of the product and from fact 1, by induction on the number of cycles read.
  3. Every proper cell lies on the path of exactly one name. The cell qq in cycle cc with name ss is matched when v=sv = s at cycle cc, and vv at cycle cc is π<c(y)\pi_{<c}(y) for the name yy whose path is followed (here π<c\pi_{<c} is the product of the cycles before cc). So qq lies on the path of y=π<c−1(s)y = \pi_{<c}^{-1}(s) and on no other.
  4. A pass of the name xx starts at the first cell q1(x)q_1(x) of the formula that has the name xx. No cycle before q1(x)q_1(x) contains xx, so v=xv = x when the pass arrives at q1(x)q_1(x), and q1(x)q_1(x) lies on the path of xx by fact 3. The cells on the path of xx are tagged only by the pass of xx.

The algorithm keeps this invariant: when A2 runs, the names of the closed output cycles form a union of orbits, and the pass of every such name has run, so all cells on their paths are tagged. Hence a name ss that is not in a closed cycle has the cell q1(s)q_1(s) untagged, and A2 does not stop while such a name exists. Let q0q_0 be the leftmost untagged proper cell and let ss be its name. The cell q1(s)q_1(s) is untagged, and it is not to the right of q0q_0, so q1(s)=q0q_1(s) = q_0. The pass of ss then starts exactly at q0q_0, and the cells to the left of q0q_0 do not change vv in this pass. So the first pass of the output cycle can start after q0q_0 with vv set to the symbol that follows q0q_0.

The passes of A3 and A4 follow s,π(s),π2(s),…s, \pi(s), \pi^2(s), \ldots by fact 2 until vv returns to START. This closes an orbit of π\pi, and the passes tag the paths of all its names. The orbits that the algorithm writes are disjoint, so each name is written once. A name of the formula that is not written has an untagged first cell, so A2 would not have stopped. A name with an orbit of length 1 gives the cycle (START)(\text{START}), which A5 deletes. □\square

Termination. Each execution of A2 tags at least one cell, and A3 and A4 tag more. The formula has finitely many cells. Each pass of A3 ends at the right end. Each execution of A4 starts a new pass only after A3 has output one more element of the cycle, and the orbit is finite, so the cycle closes after at most NN passes. Hence the algorithm stops.

Cost. Let NN be the number of distinct names. There are NN passes in A3 (one for each output element, including the singleton cycles) and U+1U + 1 searches in A2, where UU is the number of output cycles with the singletons counted. Each pass costs a number of steps that is linear in the number 16X−116X - 1 of cells. So the work is of the order N⋅XN \cdot X. Program A below makes this exact.

Program (MIX program for Algorithm A, TAOCP Program 1.3.3A). The program reads XX cards of 16 fields into a table of 16X16X cells, one MIX word for each field. A field holds a name of up to five characters, a parenthesis or blanks. The last cell holds an equals sign that ends the input. The program runs Algorithm A on the first 16X−116X - 1 cells, removes the cycles of one name, writes the answer into an output area and prints it.

Node: Program 1.3.3A · Lean: not yet stated

The structure. The registers have fixed jobs. Register I3 is the cell pointer. Register I1 is the output pointer. Register X holds the value vv (the book calls it CURRENT) as a negative number. Register A holds the word "(" during the main work. The cell count 16X−116X - 1 is kept in a memory word. Cell tags are signs: after step A1 an untagged name cell holds its name as a positive number, and a tagged cell holds it as a negative number. The comparisons of the pass look only at bytes 1 to 5 of a cell, so a tagged cell still matches its name. The program has five parts.

  1. Setup and tagging (step A1). A loop walks over all cells once. For a "(" cell it tags the parenthesis, steps to the first symbol of the cycle (blank cells are skipped) and keeps that symbol, tagged, in register X. For a ")" cell it stores the kept symbol in its place (the closing copy). Other cells pass unchanged.
  2. The search of step A2. Register I3 is reset to the first cell, and the loop reads cells one at a time, looking for a cell that is untagged and not blank. If I3 reaches the end of the table, the program leaves the loop for the output.
  3. The start of an output cycle. The program writes "(" and the first name, saves the name as START, and tags the cell. It then reads the symbol after it into register X. The pass continues from that point. This part runs once for each output cycle.
  4. The pass (steps A3 and A4). A loop compares register X with the name in the current cell. A match tags the cell and loads the next cell into X, and the loop goes on two cells further. A mismatch moves on one cell. At the end of the table, X holds the new element. If X differs from START, the program writes it to the output, resets I3 to the first cell, and starts a new pass.
  5. The closing (step A5). The program writes ")" and compares the word three places back in the output with "(". If they are equal, the cycle has one name, and the program moves I1 back three places. Then control goes back to the search.

After the end of the search, a short tail writes () if the output is empty, pads the output area with blanks, prints it and halts. When the answer fits on one printed line, the tail takes 57u57u before the halt, and 45u45u of this is a block move of 22 words (1+2⋅22=451 + 2 \cdot 22 = 45). Each further printed line adds 5u5u, and an empty answer adds 5u5u for the move of (). The time formulas below leave this tail out, as they leave out input and output.

The frequencies. The book names the number of runs of each part of the program by a letter, and C1 uses the same letters. The table gives each letter, the work of one run and its time in uu. The times use the standard MIX values: a load, a store or a comparison takes 2u2u, a MOVE of mm words takes (1+2m)u(1 + 2m)u, and the other instructions here take 1u1u.

Letter Work of one run Time
(once) finish the cell count and store it, reset I3 before A1, load "(" into rA, point I1 at the output area 7
AA A1: read a cell with its sign reversed and test it for "(" 5
BB A1 at a "(": tag it, step to the next cell, load that symbol with its sign reversed into rX, test it for blank 6
CC A1: test the cell for ")", step I3, test for the end of the table 7
DD A1 at a ")": store the tagged first symbol in its place 2
EE A2: reset I3 to the first cell 1
FF A2: read a cell with its sign reversed and test for an untagged name 3
GG A2: step I3, test for the end of the table 4
HH open an output cycle: write "(" and the name, save START 8
JJ tag a cell, step I3, load the next symbol into rX as a negative magnitude, test it for blank 6
KK A3: compare the magnitudes of rX and the cell, branch on a match 3
LL A3: step I3, test for the end of the table 4
PP end of a pass: compare rX with START 3
QQ write the new element, step I1, reset I3 4
RR close a cycle: write ")" and test for a cycle of one name 6
SS remove a cycle of one name from the output 2

The jump after the blank test of BB and the jump that skips a blank cell after a match run only when blank cells stand inside the formula. As in the book, the analysis assumes that the blank cells are all at the right end, after the last ")".

Correctness. Each part does one step of Algorithm A on the table. The one point that needs care is the sign. The search of part 2 sees a cell as untagged when the cell is positive, and the tagging of A1 makes every "(" and every closing copy negative, so the search finds only name cells. The pass of part 4 ignores the sign, as the step A3 of the algorithm requires. By the correctness of Algorithm A, the output is the cycle form of the product. □\square

Analysis (the time of Program A by its frequencies, TAOCP eq. 1.3.3(7)). Leaving out input, output and the tail, Program A runs for

(7+5A+6B+7C+2D+E+3F+4G+8H+6J+3K+4L+3P+4Q+6R+2S)u.(7 + 5A + 6B + 7C + 2D + E + 3F + 4G + 8H + 6J + 3K + 4L + 3P + 4Q + 6R + 2S)u.

Node: 1.3.3-(7) · Lean: not yet stated

Explanation. Formula (7) is a weighted sum of 15 unknown counts. To use it, the counts must be tied to the data: the number of cards, the number of cycles in the input, and so on. Equations (8) to (17) make this tie with two tools. Kirchhoff's first law says that the number of times that control enters a part equals the number of times that control leaves it. The other tool is a direct reading of what a part does: a part that runs once for each "(" has a frequency equal to the number of cycles in the input. The constant 7 is the time of the five instructions that run once: 1u1u, 2u2u, 1u1u, 2u2u and 1u1u.

Example. C1 ran the program on the formula Φ=(a b c)(a b)(d e)\Phi = (a\,b\,c)(a\,b)(d\,e) (13 fields on one card, so X=1X = 1, and the table has 16X−1=1516X - 1 = 15 cells, the last two blank, and one more cell with "="). The measured frequencies are

AA BB CC DD EE FF GG HH JJ KK LL PP QQ RR SS
12 3 12 3 4 31 28 3 7 52 55 5 2 3 1

and (7) gives 7+60+18+84+6+4+93+112+24+42+156+220+15+8+18+2=8697 + 60 + 18 + 84 + 6 + 4 + 93 + 112 + 24 + 42 + 156 + 220 + 15 + 8 + 18 + 2 = 869. The run on the simulator took 869u869u before the tail and 926u926u before the halt, and 926−869=57926 - 869 = 57 is the tail. The output was (BC)(DE) (the names are upper case letters on the cards).

Proof. Each letter in the table counts the runs of a group of instructions that always run together, so the time of the group is its frequency times the time of one run. The sum of the 16 rows of the table is (7). □\square

Analysis (the relations of Kirchhoff's law, TAOCP eq. 1.3.3(8)). The frequencies of Program A satisfy

A=C,E=R+1,F=R+G,H=R,K=L−R,Q=P−R.A = C, \qquad E = R + 1, \qquad F = R + G, \qquad H = R, \qquad K = L - R, \qquad Q = P - R.

Node: 1.3.3-(8) · Lean: not yet stated

Explanation. Each relation balances the flow of control into a part of the program against the flow out of it. The six relations remove six of the fifteen unknowns of (7).

Example. In the run on Φ\Phi: A=12=CA = 12 = C, E=4=3+1E = 4 = 3 + 1, F=31=3+28F = 31 = 3 + 28, H=3=RH = 3 = R, K=52=55−3K = 52 = 55 - 3 and Q=2=5−3Q = 2 = 5 - 3.

Proof. The loop of A1 enters part AA at its head and leaves through part CC at its end, with no other exit, so A=CA = C. The search is entered once after A1 and once after each closing, so E=1+RE = 1 + R. Each read FF of the search either finds an untagged name, which opens a cycle (HH times), or passes on to the step GG. So F=H+GF = H + G. A cycle that opens is closed once, and only an open cycle is closed, so H=RH = R, and then F=R+GF = R + G. The step LL of the pass is entered after each failed comparison, that is K−(J−H)K - (J - H) times (each match leads to JJ, and J−HJ - H of the runs of JJ come from a match, since HH of them come from the start of a cycle), and after each run of JJ. So L=K−J+H+J=K+HL = K - J + H + J = K + H, which is K=L−RK = L - R. A pass ends in PP and goes on either to QQ (a new element) or to RR (the closing), so P=Q+RP = Q + R. □\square

Analysis (the number of cells, TAOCP eq. 1.3.3(9)). The loop of A1 steps over every cell of the table once, so

B+C=16X−1.B + C = 16X - 1.

Node: 1.3.3-(9) · Lean: not yet stated

Explanation. Each run of CC moves the cell pointer by one. A "(" moves it by one more in BB, to step over the first symbol of the cycle. The table has 16X−116X - 1 cells before the final equals sign.

Example. 3+12=15=16⋅1−13 + 12 = 15 = 16 \cdot 1 - 1.

Proof. In the loop of A1, the pointer I3 starts at 00, and the loop stops when the pointer reaches the cell count 16X−116X - 1. The pointer grows only in BB and in CC, by one each time, and CC compares it with the count after each step. Part BB never moves the pointer past the end, because the first symbol of a cycle lies before its ")". So the pointer moves B+CB + C cells in all, and this number is 16X−116X - 1. □\square

Analysis (the number of "(" cells, TAOCP eq. 1.3.3(10)). BB is the number of "(" cells, which is MM, the number of cycles of the input.

Node: 1.3.3-(10) · Lean: not yet stated

Explanation. Part BB runs once for each opening parenthesis that the loop of A1 meets, and each cycle of the input has one opening parenthesis.

Example. The formula Φ\Phi has M=3M = 3 cycles, and B=3B = 3.

Proof. The test before BB is true for exactly the cells that hold "(". The loop of A1 meets every "(" cell, because BB steps over the cell after a "(", and that cell is a name. Every cycle of the input has one such cell, and no other cell has the word "(". □\square

Analysis (the number of ")" cells, TAOCP eq. 1.3.3(11)). DD is the number of ")" cells, which is also MM.

Node: 1.3.3-(11) · Lean: not yet stated

Explanation. Part DD stores a closing copy in place of a ")", once for each cycle of the input.

Example. D=3=MD = 3 = M in the run on Φ\Phi.

Proof. The test before DD is true for exactly the cells that hold ")". The loop of A1 meets every such cell, and each cycle of the input ends with one ")". □\square

Analysis (the two counts of parentheses are equal, TAOCP eq. 1.3.3(12)). B=DB = D.

Node: 1.3.3-(12) · Lean: not yet stated

Explanation. This relation does not follow from Kirchhoff's law, which sees only the flow of control. It comes from the data: each cycle has one "(" and one ")".

Example. B=3=DB = 3 = D in the run on Φ\Phi.

Proof. Both sides equal MM by eqs. (10) and (11). □\square

Analysis (the number of output cycles, TAOCP eq. 1.3.3(13)). H=UH = U, the number of cycles of the output, with the cycles of one name counted.

Node: 1.3.3-(13) · Lean: not yet stated

Explanation. Part HH opens one output cycle each time it runs. By eq. (8), R=HR = H, so the closing part runs UU times as well.

Example. H=3H = 3, and the product of Φ\Phi has the three cycles (a)(b c)(d e)(a)(b\,c)(d\,e).

Proof. The algorithm writes one cycle for each orbit of the product, the fixed names included, before it removes the cycles of one name. There are UU orbits, and each one is opened once. □\square

Analysis (the number of tags in the passes, TAOCP eq. 1.3.3(14)). J=Y−2MJ = Y - 2M, the number of name cells of the input.

Node: 1.3.3-(14) · Lean: not yet stated

Explanation. The quantity YY counts the nonblank fields of the input, the parentheses included. Each cycle has two parentheses, so the name cells number Y−2MY - 2M. Part JJ tags one name cell each time it runs.

Example. Y=13Y = 13 and M=3M = 3, so J=13−6=7J = 13 - 6 = 7. Indeed Φ\Phi has seven name cells (a,b,c,a,b,d,ea, b, c, a, b, d, e), and the run had J=7J = 7.

Proof. The nonblank cells are the name cells and the M+MM + M parentheses (eqs. (10) and (11)), so there are Y−2MY - 2M name cells. Part JJ runs once at the start of each output cycle, to tag the first name, and once after each match of the pass. Every name cell lies on the path of exactly one name (fact 3 of the correctness proof of Algorithm A), and it is tagged once, when the pass of that name meets it. A closing copy is never matched (fact 1), and a "(" never equals a name. So JJ is the number of name cells. □\square

Analysis (the number of distinct names, TAOCP eq. 1.3.3(15)). P=H+Q=NP = H + Q = N, the number of distinct names of the input.

Node: 1.3.3-(15) · Lean: not yet stated

Explanation. Each name is written to the output once, either as the first name of a cycle (in HH) or as a later element (in QQ). A pass ends in PP after each of these writes.

Example. P=5=3+2=NP = 5 = 3 + 2 = N.

Proof. Each name of the input lies in exactly one orbit of the product, so it is written once, the fixed names included. The HH starts write HH names and QQ writes the others, so H+Q=NH + Q = N. By eq. (8), Q=P−RQ = P - R and R=HR = H, so P=H+Q=NP = H + Q = N. □\square

Analysis (the cycles of one name, TAOCP eq. 1.3.3(16)). S=VS = V, the number of cycles of one name in the output.

Node: 1.3.3-(16) · Lean: not yet stated

Explanation. Part SS removes each cycle of one name from the output, once.

Example. S=1=VS = 1 = V for Φ\Phi, because aa is fixed.

Proof. The test before SS compares the word three places before the output pointer with "(". After a ")" is written, this word is "(" exactly when the cycle just closed has one name. The test runs once for each closed cycle, and it is true for the VV cycles of one name. □\square

Analysis (the total number of steps of the pointer, TAOCP eq. 1.3.3(17)). The cell pointer moves (B+C)(P+1)(B + C)(P + 1) cells in the search and the passes:

G+J+L=(B+C)(P+1).G + J + L = (B + C)(P + 1).

Node: 1.3.3-(17) · Lean: not yet stated

Explanation. After A1, the three parts GG, JJ and LL are the only places where the pointer I3 grows. Each run of a part adds one to the pointer. Kirchhoff's law cannot give this relation, because it does not see where the pointer is, and the proof uses the meaning of the pointer. By eqs. (9) and (15), the right side is (16X−1)(N+1)(16X - 1)(N + 1).

Example. 28+7+55=90=15⋅628 + 7 + 55 = 90 = 15 \cdot 6.

Proof. The pointer is reset to the first cell in EE (at each search) and in QQ (at each new pass). After a reset, the pointer travels to the cell count B+CB + C before the next reset. The search and the pass compare it with the count after each step, and neither loop leaves early, except at a match. A search that finds a name goes on as a pass from the same place, and a match in a pass moves the pointer twice (once in JJ and once in LL). A match never moves the pointer past the end, because the last cell of each cycle is a closing copy, which a pass never matches (fact 1 of the correctness proof of Algorithm A). So each reset is followed by exactly B+CB + C unit steps. The number of resets is E+Q=(R+1)+(P−R)=P+1E + Q = (R + 1) + (P - R) = P + 1 by eq. (8). □\square

Analysis (the running time of Program A, TAOCP eq. 1.3.3(18)). With the data quantities of eq. (19), the time of Program A, exclusive of input and output, is

(112NX+304X−2M−Y+11U+2V−11)u.\bigl(112NX + 304X - 2M - Y + 11U + 2V - 11\bigr)u.

Node: 1.3.3-(18) · Lean: not yet stated

Explanation. The formula is linear in XX, MM, YY, UU and VV, and it has one term in the product NXNX. This term dominates when the number of names and the number of cards both grow: the program makes a full pass over the table for each of the NN names, and the table has 16X−116X - 1 cells.

Example. For Φ\Phi: X=1X = 1, N=5N = 5, M=3M = 3, Y=13Y = 13, U=3U = 3, V=1V = 1. The formula gives 560+304−6−13+33+2−11=869560 + 304 - 6 - 13 + 33 + 2 - 11 = 869, the measured time. C1 also checked the formula against the simulator on 150 random formulas with up to 4 cards, with no difference.

Proof. Eqs. (8) to (16) give A=C=16X−1−MA = C = 16X - 1 - M, B=D=MB = D = M, H=R=UH = R = U, E=U+1E = U + 1, F=U+GF = U + G, K=L−UK = L - U, P=NP = N, Q=N−UQ = N - U, S=VS = V and J=Y−2MJ = Y - 2M. Put them into (7):

7+12(16X−1−M)+8M+(U+1)+3(U+G)+4G+8U+6J+3(L−U)+4L+3N+4(N−U)+6U+2V.7 + 12(16X - 1 - M) + 8M + (U + 1) + 3(U + G) + 4G + 8U + 6J + 3(L - U) + 4L + 3N + 4(N - U) + 6U + 2V.

The terms in UU are U+3U+8U−3U−4U+6U=11UU + 3U + 8U - 3U - 4U + 6U = 11U. So the time is 8+12(16X−1)−4M+11U+2V+7N+7(G+L)+6J8 + 12(16X - 1) - 4M + 11U + 2V + 7N + 7(G + L) + 6J. By eq. (17), G+L=(16X−1)(N+1)−JG + L = (16X - 1)(N + 1) - J, so 7(G+L)+6J=7(16X−1)(N+1)−J7(G + L) + 6J = 7(16X - 1)(N + 1) - J, and −J=−Y+2M-J = -Y + 2M. The time becomes

8+12(16X−1)+7(16X−1)(N+1)+7N−2M−Y+11U+2V.8 + 12(16X - 1) + 7(16X - 1)(N + 1) + 7N - 2M - Y + 11U + 2V.

Now 7(16X−1)(N+1)+7N=112NX+112X−77(16X - 1)(N + 1) + 7N = 112NX + 112X - 7 and 8+12(16X−1)=192X−48 + 12(16X - 1) = 192X - 4. The sum is 112NX+304X−11−2M−Y+11U+2V112NX + 304X - 11 - 2M - Y + 11U + 2V. □\square

Definition (the data quantities, TAOCP eq. 1.3.3(19)). For an input formula, XX is the number of cards, YY is the number of nonblank fields (the final equals sign is not counted), MM is the number of cycles of the input, NN is the number of distinct names, UU is the number of cycles of the output with the cycles of one name counted, and VV is the number of cycles of one name in the output.

Node: 1.3.3-(19) · Lean: not yet stated

Explanation. These six numbers carry all the dependence of the running time on the data. The first four describe the input, and the last two describe the answer. The numbers UU and VV are known only after the work. A bound on the time uses the facts U≤NU \le N and V≤UV \le U.

Example. Take the formula (a b)(b c)(c d)(d e)(a\,b)(b\,c)(c\,d)(d\,e). It has 16 nonblank fields, and with the final equals sign it needs 17 fields, so X=2X = 2, Y=16Y = 16, M=4M = 4 and N=5N = 5. Follow aa: the first factor sends it to bb, the second sends bb to cc, the third sends cc to dd, and the fourth sends dd to ee. In the same way e↦de \mapsto d, d↦cd \mapsto c, c↦bc \mapsto b and b↦ab \mapsto a. The product is the single cycle (a e d c b)(a\,e\,d\,c\,b), so U=1U = 1 and V=0V = 0. Eq. (18) gives 1120+608−8−16+11+0−11=17041120 + 608 - 8 - 16 + 11 + 0 - 11 = 1704. The simulator measured 1704u1704u before the tail and printed (AEDCB).

Proof. The definition is a list of names for counts. The bounds U≤NU \le N and V≤UV \le U hold because the orbits of the product partition the NN names and each cycle of one name is an orbit. □\square

Algorithm (multiplication of permutations in cycle form with a table, TAOCP Algorithm 1.3.3B). Input and output are those of Algorithm A. The algorithm reads the formula once from right to left. It keeps a list of the names that it has met, and for each name jj in the list a table entry T[j]T[j]. After the algorithm has read a suffix of the formula, T[j]T[j] is the image of the name jj under the product of that suffix. A register ZZ carries a value from one symbol to the next inside a cycle. When the whole formula has been read, TT is the product, and the algorithm writes its cycles.

Node: Algorithm 1.3.3B · Lean: not yet stated

The idea. Let SS be a suffix of the formula and let (x1 x2…xk)(x_1\,x_2 \ldots x_k) be the cycle just before it. The product of the longer suffix is the cycle followed by SS. A name xix_i with i<ki < k goes to xi+1x_{i+1} in the cycle, and then to T[xi+1]T[x_{i+1}] in SS. The name xkx_k goes to x1x_1 and then to T[x1]T[x_1]. The names outside the cycle are unchanged. So the new table is T′[xi]=T[xi+1]T'[x_i] = T[x_{i+1}] for i<ki < k, and T′[xk]=T[x1]T'[x_k] = T[x_1]. A right-to-left reading of the cycle can make this change with one pass and one register: read xkx_k, then xk−1x_{k-1}, down to x1x_1. At each name, put the old content of the register into the entry of the name and take the old entry into the register. The first entry that is changed (the entry of xkx_k) has no value to receive, so the algorithm puts a hole there and fills the hole at the end with the value of x1x_1.

The steps. In the steps, the list of names is LL, with L[1],L[2],…L[1], L[2], \ldots in order of first arrival, and ss is the length of LL. The symbol 00 means "no value" (TT values are always at least 11).

B1. s <- 0. Set the reading position to the right end of the formula.
B2. Read the next symbol from the right. If the formula is exhausted, go to B6.
    If the symbol is ")", set Z <- 0 and hole <- 0 and repeat B2.
    If the symbol is "(", go to B5.
    Else the symbol is a name; go to B3.
B3. Find j with L[j] = name. If no j exists, set s <- s+1, L[s] <- name,
    T[s] <- s, and j <- s.
B4. Swap: t <- T[j], T[j] <- Z, Z <- t. If the old Z was 0, set hole <- j.
    Go to B2.
B5. T[hole] <- Z. Go to B2.
B6. For m = s, s-1, ..., 1: if m is unmarked and T[m] != m, write a cycle
    starting at m: follow m, T[m], T[T[m]], ... writing L[.] and marking
    each, until the start returns. Write "(" before and ")" after.

A worked run. The formula is Φ=(a b c)(a b)(d e)\Phi = (a\,b\,c)(a\,b)(d\,e) again. The algorithm reads from the right. The list LL grows as e,d,b,a,ce, d, b, a, c (so the names have the numbers e=1e = 1, d=2d = 2, b=3b = 3, a=4a = 4, c=5c = 5). The rows show T[1..5]T[1..5] (a 0 is a hole, and a blank is a name not yet in the list) and ZZ after each symbol.

Symbol read ZZ after TT after
) 0
ee 1 0
dd 2 0, 1
( 2 2, 1
) 0 2, 1
bb 3 2, 1, 0
aa 4 2, 1, 0, 3
( 4 2, 1, 4, 3
) 0 2, 1, 4, 3
cc 5 2, 1, 4, 3, 0
bb 4 2, 1, 5, 3, 0
aa 3 2, 1, 5, 4, 0
( 3 2, 1, 5, 4, 3

Check the rows of the last cycle (a b c)(a\,b\,c). After ), the register is Z=0Z = 0. The name cc has number 55. It is new, so T[5]=5T[5] = 5. The swap gives Z=5Z = 5 and T[5]=0T[5] = 0, and the hole is 55. The name bb has number 33 with T[3]=4T[3] = 4 (before this row, T[3]T[3] held the image of bb under the suffix (a b)(d e)(a\,b)(d\,e), which is aa, number 44). The swap puts Z=5Z = 5 into T[3]T[3] and takes 44 into ZZ. The name aa (number 44) has T[4]=3T[4] = 3 before the swap (under the suffix, a↦ba \mapsto b, number 33), and the swap puts 44 into T[4]T[4] and takes 33 into ZZ. At (, T[5]←3T[5] \leftarrow 3. The final table is T=[2,1,5,4,3]T = [2, 1, 5, 4, 3]. Its cycles, by the list e,d,b,a,ce, d, b, a, c, are: 1↔21 \leftrightarrow 2 (that is e↔de \leftrightarrow d), 3→5→33 \to 5 \to 3 (that is b→c→bb \to c \to b), and 44 is fixed (aa). The product is (b c)(d e)(b\,c)(d\,e), the same as the answer of Algorithm A. The output step starts from m=5m = 5 (the name cc) and writes (c b)(c\,b), skips m=4m = 4 (fixed) and m=3m = 3 (marked), starts at m=2m = 2 and writes (d e)(d\,e), and skips m=1m = 1. The written form is (c b)(d e)(c\,b)(d\,e).

Correctness. Claim: after B4 or B5 has handled all symbols of a suffix SS, T[j]T[j] is the image of L[j]L[j] under the product of SS for every name jj in the list, except for the entries in the cycle that is being read, where the claim holds after B5. The proof is by induction on the number of symbols read. For a name not yet in the list, the product of the suffix is the identity on it, and B3 sets T[s]=sT[s] = s, which is the identity. For a cycle (x1…xk)(x_1 \ldots x_k) read from the right, the symbols are met in the order xk,xk−1,…,x1x_k, x_{k-1}, \ldots, x_1. Let T0T_0 be the table before the cycle. When xkx_k is read, Z=0Z = 0, so B4 sets T[xk]=0T[x_k] = 0, takes Z=T0[xk]Z = T_0[x_k] and records the hole xkx_k. When xix_i is read for i<ki < k, B4 sets T[xi]=Z=T0[xi+1]T[x_i] = Z = T_0[x_{i+1}] (by induction on ii from k−1k - 1 down) and takes Z=T0[xi]Z = T_0[x_i]. At the "(", Z=T0[x1]Z = T_0[x_1], and B5 sets T[xk]=T0[x1]T[x_k] = T_0[x_1]. Hence the new table is T′[xi]=T0[xi+1]T'[x_i] = T_0[x_{i+1}] and T′[xk]=T0[x1]T'[x_k] = T_0[x_1], as the idea requires. Names outside the cycle are not touched. A name that is read for the first time inside the cycle gets T0[x]=xT_0[x] = x (the identity) in B3, which is the correct image under the empty suffix. One check is the case k=1k = 1: T[x1]←0T[x_1] \leftarrow 0, Z←T0[x1]Z \leftarrow T_0[x_1], then B5 sets T[x1]←T0[x1]T[x_1] \leftarrow T_0[x_1], and nothing changes. At the end of the formula TT is the product of the whole formula, and the cycle writing of B6 is the construction of the proof of the cycle form from the table. □\square

Termination. B2 reads one symbol each time and the formula is finite. B3 searches a finite list. B6 marks at least one entry in each cycle that it writes, and the loop on mm is finite.

Cost. The algorithm does a constant amount of work for each symbol, plus the search of B3. The search takes at most the length of the list. So the time is linear in the length of the formula when the names are small numbers (no search), and it is at most the length times NN when the names must be looked up. Program B has the exact count.

Program (MIX program for Algorithm B, TAOCP Program 1.3.3B). The program takes the same card input as Program A. It reads the table of 16X−116X - 1 cells from the right end to the left end. A search of the list of names uses a sentinel at the head of the list so that the loop has only one test.

Node: Program 1.3.3B · Lean: not yet stated

The structure. Register I2 is the reading position and it counts down. Register X is ZZ (a value carried in a cycle). Register I3 is ss, the length of the list. Register I4 is the search index and, after the search, the number jj of the name. Register I1 is the hole. The list of names is the array X and the table is T. The five parts are as follows.

  1. Fetch. The program decreases I2 and loads the cell. A blank cell ends the cycle part (it only advances the loop). A ")" resets register X to 00. A "(" stores the register in the hole.
  2. Search. For a name, the program stores it at the head of the list (the sentinel), and loops down the list from the top until the name matches. A match at the head means that the name is new.
  3. Insert. A new name gets the next number, and its table entry is set to the number itself.
  4. Rotate. The program loads the old table entry, stores register X in its place, and moves the old entry into register X (a rotation of rA and rX by five bytes does this swap in one instruction). If the old value of X was 00, the program remembers the number as the hole.
  5. Write. After the last cell, a loop on mm from ss down to 11 writes the cycles by following TT and marks the written names in the list by changing their sign.

The groups and their times. As in Program A, the instructions are grouped by equal frequency. Let W=16X−1W = 16X - 1, let E=Y−2ME = Y - 2M be the number of names in the input, and let FF be the number of steps of the search loop. The table gives each group, its time in uu for one run and the frequency.

Group Work Time Frequency
setup start 2 1
restart at ")" Z←0Z \leftarrow 0 1 M+1M + 1
fetch decrease position, load cell, test blank 4 WW
test ")" compare and branch 3 YY
test "(" compare and branch 3 Y−MY - M
search set up set the index and the sentinel 3 EE
search step one step of the loop 4 FF
search result test whether found 1 EE
new name increase ss, store name and table entry 6 NN
rotate swap of the table entry and ZZ 7 EE
hole remember the hole 2 MM
left parenthesis store ZZ at the hole 2 MM
continue test the position 1 W−Y+MW - Y + M
output set up pointer and test for s=0s = 0 2 1
output loop test load mark, test 3 NN
fixed test compare T[m]T[m] with mm 3 UU
cycle open and close write "(" and ")" 6 U−VU - V
cycle body one name written and marked 10 N−VN - V
step down decrease mm and test 2 NN

C1 ran the program on Φ=(a b c)(a b)(d e)\Phi = (a\,b\,c)(a\,b)(d\,e): X=1X = 1, W=15W = 15, Y=13Y = 13, M=3M = 3, N=5N = 5, U=3U = 3, V=1V = 1, and the search made F=20F = 20 steps. The program wrote (CB)(DE). It ran for 427u427u up to the end of the output loop, and for 485u485u up to and including the halt, since the output tail is the one of Program A (57u57u, then the halt). The sum of the table is 2+4+60+39+30+21+80+7+30+49+6+6+5+2+15+9+12+40+10=4272 + 4 + 60 + 39 + 30 + 21 + 80 + 7 + 30 + 49 + 6 + 6 + 5 + 2 + 15 + 9 + 12 + 40 + 10 = 427, as measured.

Correctness. The program follows the steps of Algorithm B. The sentinel makes the search loop safe: the name is stored at the head of the list before the loop, so the loop ends at the latest at the head, and a match at the head means "not found". The operations on registers do what the steps say, with the one instruction that swaps rA and rX. The output loop visits m=s,s−1,…,1m = s, s - 1, \ldots, 1. It skips a name whose mark is set and a fixed name (T[m]=mT[m] = m). For a name that is neither, it writes the whole cycle that follows mm and marks each of its names, so a cycle is written once. By the correctness of Algorithm B, the output is the cycle form of the product. □\square

Analysis (running time of Program B, TAOCP exercise 1.3.3-10 and the text of Program B). The time of Program B, exclusive of input and output, is given below. The symbols are X,Y,M,N,U,VX, Y, M, N, U, V from eq. 1.3.3(19), and FF is the number of steps of the search loop; the search steps satisfy E≤F≤NEE \le F \le NE with E=Y−2ME = Y - 2M. The time is

(80X+16Y−19M+4F+21N+9U−16V)u,\bigl(80X + 16Y - 19M + 4F + 21N + 9U - 16V\bigr)u,

Node: 1.3.3-anal-progB · Lean: not yet stated

Explanation. The first part of the time is the fetch of every cell of the table and is proportional to the number of cards. The second part is the work for every name, and the term with FF is the cost of the search. If a program uses an index jj directly (the names are numbers), then FF is not needed. The NXNX term is at most 64NX64NX, because F≤NE≤N(16X−1)F \le NE \le N(16X - 1) gives 4F≤64NX4F \le 64NX. Program A has exactly 112NX112NX as its leading term, so for large NN and XX Program B is faster by a factor of at least 112/64=1.75112/64 = 1.75 in the worst case, and the factor is much larger when the average search is short.

Example. On Φ\Phi: X=1X = 1, Y=13Y = 13, M=3M = 3, F=20F = 20, N=5N = 5, U=3U = 3, V=1V = 1. The formula gives 80+208−57+80+105+27−16=42780 + 208 - 57 + 80 + 105 + 27 - 16 = 427, as measured. For the same formula, Program A takes 869u869u. The relation E≤F≤NEE \le F \le NE reads 7≤20≤357 \le 20 \le 35.

Proof. The frequencies follow from the structure. Each of the W=16X−1W = 16X - 1 cells is fetched once. A cell is blank, ")" , "(" or a name. The nonblank cells number YY and the test for ")" runs for each of them. The ")" cells number MM, so the test for "(" runs Y−MY - M times. The "(" cells number MM, so the names number E=Y−2ME = Y - 2M. The search runs once for each name. A name is new once for each distinct name, which is NN times. The rotate group runs once for each name. The hole is recorded once for each cycle (the first name that is read after a ")" finds Z=0Z = 0), so it runs MM times, and the "(" group runs MM times. The continue group is reached from a blank cell (W−YW - Y times) and from a "(" (MM times). The output loop tests each of the NN names once (the loop on mm has one entry for each name). The test for a fixed name runs for each unmarked name, which is once for each cycle of TT (the number UU of cycles, singletons included). Of these, VV are fixed, so U−VU - V cycles are written. Each of the N−VN - V names in a written cycle is written once. Add the group times:

2+(M+1)+4W+3Y+3(Y−M)+3E+4F+E+6N+7E+2M+2M+(W−Y+M)+2+3N+3U+6(U−V)+10(N−V)+2N.2 + (M + 1) + 4W + 3Y + 3(Y - M) + 3E + 4F + E + 6N + 7E + 2M + 2M + (W - Y + M) + 2 + 3N + 3U + 6(U - V) + 10(N - V) + 2N.

The constants are 2+1+2=52 + 1 + 2 = 5. The terms in MM: M−3M+2M+2M+M=3MM - 3M + 2M + 2M + M = 3M. The terms in WW: 4W+W=5W4W + W = 5W. The terms in YY: 3Y+3Y−Y=5Y3Y + 3Y - Y = 5Y. The terms in EE are 3E+E+7E=11E=11Y−22M3E + E + 7E = 11E = 11Y - 22M. The terms in NN: 6N+3N+10N+2N=21N6N + 3N + 10N + 2N = 21N. The terms in UU and VV: 3U+6U=9U3U + 6U = 9U and −6V−10V=−16V-6V - 10V = -16V. So the total is 5+5W+16Y−19M+4F+21N+9U−16V5 + 5W + 16Y - 19M + 4F + 21N + 9U - 16V. With W=16X−1W = 16X - 1, 5+5W=80X5 + 5W = 80X. For the bounds on FF: a search for a name that sits at place pp of a list of length ss takes s−p+1s - p + 1 steps, and a search for a new name takes s+1s + 1 steps with s≤N−1s \le N - 1. Every search takes at least one step and at most NN steps, so E≤F≤NEE \le F \le NE. □\square

Definition (the inverse of a permutation, TAOCP Section 1.3.3). For a permutation π\pi, its inverse π−\pi^{-} is the unique permutation with π−(π(x))=x\pi^{-}(\pi(x)) = x for all xx. In the two-line form, exchange the two rows. In the cycle form, reverse the order of the names in each cycle.

Node: 1.3.3-def-inverse · Lean: not yet stated

Explanation. The inverse undoes the permutation, so ππ−\pi\pi^{-} (first π\pi, then π−\pi^{-}) is the identity, and so is π−π\pi^{-}\pi. The map π↦π−\pi \mapsto \pi^{-} is its own inverse. The inverse of a product reverses the order: (π1π2)−=π2−π1−(\pi_1\pi_2)^{-} = \pi_2^{-}\pi_1^{-}. In Mathlib the inverse of σ : Equiv.Perm α is σ⁻¹, and Equiv.Perm.inv_def says that it is the inverse equivalence σ.symm.

Example. The permutation ρ=(a d f)(b c e)\rho = (a\,d\,f)(b\,c\,e) has the inverse (f d a)(e c b)(f\,d\,a)(e\,c\,b), which is the same as (a f d)(b e c)(a\,f\,d)(b\,e\,c). Check: ρ(a)=d\rho(a) = d and the inverse sends dd to aa. Also ρ(b)=c\rho(b) = c and the inverse sends cc to bb. For the array form on {1,…,4}\{1, \ldots, 4\}, take the arrangement [3,1,4,2][3, 1, 4, 2] (that is X[1]=3X[1] = 3, X[2]=1X[2] = 1, X[3]=4X[3] = 4, X[4]=2X[4] = 2). The inverse has X−[3]=1X^{-}[3] = 1, X−[1]=2X^{-}[1] = 2, X−[4]=3X^{-}[4] = 3, X−[2]=4X^{-}[2] = 4, which is [2,4,1,3][2, 4, 1, 3]. In cycle form, [3,1,4,2]=(1 3 4 2)[3, 1, 4, 2] = (1\,3\,4\,2) and [2,4,1,3]=(1 2 4 3)[2, 4, 1, 3] = (1\,2\,4\,3), the reversed cycle.

Proof. The inverse of a bijection is a bijection, and it exists and is unique. The two-line rule: the column (xπ(x))\binom{x}{\pi(x)} becomes (π(x)x)\binom{\pi(x)}{x}. For the cycle rule, if π\pi has the cycle (x1…xk)(x_1 \ldots x_k), then π−(xi+1)=xi\pi^{-}(x_{i+1}) = x_i for i<ki < k and π−(x1)=xk\pi^{-}(x_1) = x_k, which is the cycle (xk xk−1…x1)(x_k\,x_{k-1} \ldots x_1), the reversed one. For the product, (π2−π1−)(\pi_2^{-}\pi_1^{-}) applied after π1π2\pi_1\pi_2 gives π1−(π2−(π2(π1(x))))=x\pi_1^{-}(\pi_2^{-}(\pi_2(\pi_1(x)))) = x. □\square

Algorithm (inverse in place, with signs as marks, TAOCP Algorithm 1.3.3I). Input: an array X[1..n]X[1..n] that holds a permutation of {1,…,n}\{1, \ldots, n\} with X[k]=π(k)X[k] = \pi(k). Output: the same array with X[k]=π−(k)X[k] = \pi^{-}(k). The algorithm needs only a constant number of extra variables. It marks the entries that belong to a cycle that has been treated by a negative sign.

Node: Algorithm 1.3.3I · Lean: not yet stated

The idea. The algorithm treats the cycles one at a time, starting each from its largest name (it uses m=n,n−1,…,1m = n, n - 1, \ldots, 1 and a cycle is treated at its largest name, because the larger names have been treated before). Take a cycle m0→m1→⋯→mk−1→m0m_0 \to m_1 \to \cdots \to m_{k-1} \to m_0. The inverse has X[mt]=mt−1X[m_t] = m_{t-1}. The algorithm walks the cycle once. At each name mtm_t, it replaces X[mt]X[m_t] by the previous name with a minus sign, so X[mt]=−mt−1X[m_t] = -m_{t-1}. This is possible without losing information because the next name mt+1m_{t+1} has been read into a variable before the entry is overwritten. At the end, the entry of m0m_0 gets its final value mk−1m_{k-1} with a plus sign. The other entries of the cycle keep the minus sign, and the loop on mm flips the sign back to plus when it reaches each of them, because they are smaller than m0m_0.

The steps.

I1. m <- n, j <- -1.
I2. i <- X[m]. If i < 0, go to I5.
I3. X[m] <- j, j <- -m, m <- i, i <- X[m].
I4. If i > 0, go to I3. Else i <- j.
I5. X[m] <- -i.
I6. m <- m - 1. If m > 0, go to I2.

A worked run. Let π=[4,7,3,1,2,5,6]\pi = [4, 7, 3, 1, 2, 5, 6] (n=7n = 7), with the cycles (1 4)(2 7 6 5)(3)(1\,4)(2\,7\,6\,5)(3). The inverse is [4,5,3,1,6,7,2][4, 5, 3, 1, 6, 7, 2]. The table shows the array after each execution of I5 (the value of mm is the value when I5 runs; for m=7m = 7 the cycle (2 7 6 5)(2\,7\,6\,5) is rewired).

mm at I2 Array after I5 What happens
7 [4,−5,3,1,−6,−7,2][4, -5, 3, 1, -6, -7, 2] the cycle of 7 is rewired; X[7]X[7] gets 2
6 [4,−5,3,1,−6,7,2][4, -5, 3, 1, -6, 7, 2] X[6]<0X[6] < 0, so the sign is flipped
5 [4,−5,3,1,6,7,2][4, -5, 3, 1, 6, 7, 2] flip
4 [−4,−5,3,1,6,7,2][-4, -5, 3, 1, 6, 7, 2] the cycle (1 4)(1\,4) is rewired at its largest name 4
3 [−4,−5,3,1,6,7,2][-4, -5, 3, 1, 6, 7, 2] the fixed point 3 gets X[3]=3X[3] = 3 again
2 [−4,5,3,1,6,7,2][-4, 5, 3, 1, 6, 7, 2] flip
1 [4,5,3,1,6,7,2][4, 5, 3, 1, 6, 7, 2] flip

The first row in detail: For m=7m = 7: i=X[7]=6>0i = X[7] = 6 > 0. I3: X[7]←−1X[7] \leftarrow -1, j←−7j \leftarrow -7, m←6m \leftarrow 6, i←X[6]=5i \leftarrow X[6] = 5. I4: i>0i > 0, so I3 again: X[6]←−7X[6] \leftarrow -7, j←−6j \leftarrow -6, m←5m \leftarrow 5, i←X[5]=2i \leftarrow X[5] = 2. Again: X[5]←−6X[5] \leftarrow -6, j←−5j \leftarrow -5, m←2m \leftarrow 2, i←X[2]=7i \leftarrow X[2] = 7. Again: X[2]←−5X[2] \leftarrow -5, j←−2j \leftarrow -2, m←7m \leftarrow 7, i←X[7]=−1i \leftarrow X[7] = -1. I4: i<0i < 0, so i←j=−2i \leftarrow j = -2. I5: X[7]←2X[7] \leftarrow 2. The array is [4,−5,3,1,−6,−7,2][4, -5, 3, 1, -6, -7, 2].

Correctness. Take the moment when the algorithm treats a cycle at its largest name m0m_0 (all names larger than m0m_0 belong to treated cycles and have final values with a plus sign, and the entries of the names smaller than m0m_0 in treated cycles have minus signs, or have been flipped to plus). Since X[m0]>0X[m_0] > 0, the algorithm enters I3. In the pass through I3, the variables are as follows. At the first run, X[m0]←j0X[m_0] \leftarrow j_0 where j0j_0 is some negative value, j←−m0j \leftarrow -m_0, m←m1=π(m0)m \leftarrow m_1 = \pi(m_0), and i←X[m1]=π(m1)=m2i \leftarrow X[m_1] = \pi(m_1) = m_2. At the tt-th run, X[mt]←−mt−1X[m_t] \leftarrow -m_{t-1}, j←−mtj \leftarrow -m_t, m←mt+1m \leftarrow m_{t+1}, i←mt+2i \leftarrow m_{t+2}. The run continues while i>0i > 0. The entries X[mt]X[m_t] for t≥1t \ge 1 are positive until they are overwritten (names of the cycle that is not yet treated, never touched), and the entry of m0m_0 is the negative value j0j_0 after the first run, so the test i>0i > 0 fails exactly when mm has come back to m0m_0 (the cycle is closed) and i=X[m0]=j0<0i = X[m_0] = j_0 < 0. At that point j=−mk−1j = -m_{k-1}. So i←−mk−1i \leftarrow -m_{k-1}, and I5 sets X[m0]←mk−1=π−(m0)X[m_0] \leftarrow m_{k-1} = \pi^{-}(m_0). The entries of m1,…,mk−1m_1, \ldots, m_{k-1} are −m0,…,−mk−2-m_0, \ldots, -m_{k-2}, which are the negatives of their inverse values. The loop on mm meets each of them later (they are smaller than m0m_0) with X[m]<0X[m] < 0, and I5 sets X[m]←−X[m]X[m] \leftarrow -X[m], the final value. For a fixed point m0m_0: I3 sets X[m0]←jX[m_0] \leftarrow j, j←−m0j \leftarrow -m_0, m←m0m \leftarrow m_0, i←X[m0]=jold<0i \leftarrow X[m_0] = j_{\text{old}} < 0; then i←j=−m0i \leftarrow j = -m_0 and I5 gives X[m0]=m0X[m_0] = m_0. A name larger than all the others of the cycle is m0m_0 because the loop meets the names in decreasing order and every name of the cycle is untreated until its cycle is reached. At the end every cycle has been treated, so X=π−X = \pi^{-}. □\square

Termination. The loop on mm goes from nn down to 11. Each I3 run advances along a cycle, and the cycle is finite and closes by the sign test. Hence the algorithm stops.

Cost. The loop of I2 runs nn times. The run of I3 happens once for each name: each name is visited once on its cycle. I5 runs nn times. The algorithm does a constant amount of work for each name, plus a constant amount for each cycle (the step i←ji \leftarrow j). The time is of the form an+bCa n + b C, where CC is the number of cycles.

Program (MIX program for Algorithm I, TAOCP Program 1.3.3I). The program holds mm in rI1 and jj in rI3. Register I2 holds −i-i, not ii: the program loads X[m]X[m] with its sign reversed. Then the test i<0i < 0 of I2 is a jump on a positive rI2, the test i>0i > 0 of I4 is a jump on a negative rI2, and the store of I5 writes −i-i with no extra work. The array is at X with X[1]X[1] at X+1. The program has four parts: a loop head that loads −X[m]-X[m] and tests its sign; the body of I3 and I4 (one store, two enter instructions, one load with the sign reversed, and the jump of I4); the change i←ji \leftarrow j, which is one enter instruction; and the store of I5 with the loop control of I6.

Node: Program 1.3.3I · Lean: not yet stated

The groups and the time. The groups are: setup (2u2u, once); load and test of I2 (3u3u, nn times); the body of I3 and I4 (7u7u, once for each name, so nn times in total); the change i←ji \leftarrow j (1u1u, once for each cycle, CC times); the store of I5 (2u2u, nn times); and the loop control (2u2u, nn times). So the time is

TI=(14n+C+2)u.T_I = (14n + C + 2)u.

Explanation. The constant 14=3+7+2+214 = 3 + 7 + 2 + 2 is the sum of the four groups that run nn times. The halt is not counted.

Example. For π=[4,7,3,1,2,5,6]\pi = [4, 7, 3, 1, 2, 5, 6], n=7n = 7 and C=3C = 3, so TI=98+3+2=103uT_I = 98 + 3 + 2 = 103u. A MIX simulator gave 103u103u before the halt. C1 also ran the program on 300 random permutations of 1 to 9 names. In each case the array became the inverse and the time was exactly 14n+C+214n + C + 2.

Proof. The load-and-test group is the head of the loop, entered for each mm, so nn times. The body of I3 runs once for each name of each cycle, which is nn times in all, because the cycles partition the names. The step i←ji \leftarrow j is made at I4 when the cycle closes, once for each cycle. The group of I5 and the loop control run once for each value of mm. Add: 2+3n+7n+C+2n+2n=14n+C+22 + 3n + 7n + C + 2n + 2n = 14n + C + 2. □\square

Algorithm (inverse in place by chains, TAOCP Algorithm 1.3.3J). Input and output are those of Algorithm I. The algorithm first negates every entry. Then it treats the names from nn down to 11. For each mm it follows a chain of positive entries until it finds a negative entry, and it uses the chain to put mm at the position π(m)\pi(m) and to repair the link of the chain.

Node: Algorithm 1.3.3J · Lean: not yet stated

The idea. After a name vv has been treated, the entry at π(v)\pi(v) must hold vv with a plus sign. The inverse of the permutation restricted to the names not yet treated is not a stored array, so the algorithm keeps it as a chain: a positive entry X[k]=vX[k] = v says "the name vv comes before kk" and links kk to vv. The negative entries mark the heads of the chains. To treat mm, the algorithm follows the chain that starts at mm until it finds a head, and then it splices the name π(m)\pi(m) out of the heads, writing mm at π(m)\pi(m).

The steps.

J1. For k = 1..n: X[k] <- -X[k]. Set m <- n.
J2. j <- m.
J3. i <- X[j]. If i > 0, set j <- i and repeat J3.
J4. X[j] <- X[-i]. X[-i] <- m.
J5. m <- m - 1. If m >= 1, go to J2.

A worked run. Take the same π=[4,7,3,1,2,5,6]\pi = [4, 7, 3, 1, 2, 5, 6]. After J1 the array is [−4,−7,−3,−1,−2,−5,−6][-4, -7, -3, -1, -2, -5, -6]. The table gives the number tt of runs of J3 and the array after J4 for each mm.

mm tt Array after J4
7 1 [−4,−7,−3,−1,−2,7,−5][-4, -7, -3, -1, -2, 7, -5]
6 2 [−4,−7,−3,−1,6,7,−2][-4, -7, -3, -1, 6, 7, -2]
5 3 [−4,5,−3,−1,6,7,−7][-4, 5, -3, -1, 6, 7, -7]
4 1 [4,5,−3,−4,6,7,−7][4, 5, -3, -4, 6, 7, -7]
3 1 [4,5,3,−4,6,7,−7][4, 5, 3, -4, 6, 7, -7]
2 4 [4,5,3,−4,6,7,2][4, 5, 3, -4, 6, 7, 2]
1 2 [4,5,3,1,6,7,2][4, 5, 3, 1, 6, 7, 2]

Check the first rows. For m=7m = 7: j=7j = 7, i=X[7]=−6≤0i = X[7] = -6 \le 0 at once. J4: X[7]←X[6]=−5X[7] \leftarrow X[6] = -5 and X[6]←7X[6] \leftarrow 7. For m=6m = 6: j=6j = 6, i=X[6]=7>0i = X[6] = 7 > 0, so j←7j \leftarrow 7, and i=X[7]=−5≤0i = X[7] = -5 \le 0. J4: X[7]←X[5]=−2X[7] \leftarrow X[5] = -2 and X[5]←6X[5] \leftarrow 6. The final array is the inverse [4,5,3,1,6,7,2][4, 5, 3, 1, 6, 7, 2]. The total number of runs of J3 is 1+2+3+1+1+4+2=141 + 2 + 3 + 1 + 1 + 4 + 2 = 14.

Correctness. Let ψ=π−\psi = \pi^{-} be the inverse (not stored). Let D={m+1,…,n}D = \{m + 1, \ldots, n\} be the names that have been treated at the start of the iteration for mm, let P={1,…,n}∖π(D)P = \{1, \ldots, n\} \setminus \pi(D), and let g:P→Pg: P \to P be the map that sends k∈Pk \in P to the first of π(k),π2(k),…\pi(k), \pi^2(k), \ldots that lies in PP. The map gg is a permutation of PP (it is the permutation π\pi with the names of π(D)\pi(D) spliced out of its cycles). Invariant: at the start of the iteration for mm, X[π(v)]=vX[\pi(v)] = v for every v∈Dv \in D, and X[k]=−g(k)X[k] = -g(k) for every k∈Pk \in P.

The invariant holds at the start. When m=nm = n, DD is empty, PP is the whole set, g=πg = \pi, and J1 has made X[k]=−π(k)X[k] = -\pi(k). Suppose that it holds for mm. Names k∈π(D)k \in \pi(D) have positive entries. The names in PP have negative entries. In J3 the chain goes from j=mj = m to ψ(j)\psi(j) as long as j∈π(D)j \in \pi(D), because then X[j]=ψ(j)>0X[j] = \psi(j) > 0. The chain stops at the first j∈Pj \in P. It stops, because the chain would return to mm only by passing through ψ(j′)=m\psi(j') = m with m∈Dm \in D, which is false. Let tt be the number of steps, so j=ψt(m)j = \psi^t(m). The names π(j),…,πt(j)=m\pi(j), \ldots, \pi^t(j) = m are in π(D)\pi(D) for t≥1t \ge 1 (each is a step of the chain), except that j=ψt(m)∈Pj = \psi^t(m) \in P itself. So the next name of the cycle after these that is in PP is πt+1(j)=π(m)\pi^{t+1}(j) = \pi(m), which is in PP because m∉Dm \notin D. Hence g(j)=π(m)g(j) = \pi(m). (For t=0t = 0, j=m∈Pj = m \in P and g(m)=π(m)g(m) = \pi(m) directly.) At J3 the final i=X[j]=−g(j)=−π(m)i = X[j] = -g(j) = -\pi(m), so −i=π(m)-i = \pi(m). J4 does two things. It sets X[j]←X[π(m)]=−g(π(m))X[j] \leftarrow X[\pi(m)] = -g(\pi(m)), and it sets X[π(m)]←mX[\pi(m)] \leftarrow m. The new sets are D′=D∪{m}D' = D \cup \{m\} and P′=P∖{π(m)}P' = P \setminus \{\pi(m)\}, and g′g' is gg with π(m)\pi(m) spliced out: g′(j)=g(π(m))g'(j) = g(\pi(m)) and g′(k)=g(k)g'(k) = g(k) for all other k∈P′k \in P'. So X[j]=−g′(j)X[j] = -g'(j), the entries X[k]X[k] of the other names of P′P' are unchanged and equal to −g′(k)-g'(k), and X[π(m)]=mX[\pi(m)] = m gives the new case v=mv = m of the first part. The case j=π(m)j = \pi(m) (the chain ends at the name that is removed) is covered by the order of the two stores: the first store changes nothing and the second sets X[π(m)]=mX[\pi(m)] = m. After the iteration for m=1m = 1, DD is the full set, PP is empty, and X[π(v)]=vX[\pi(v)] = v for all vv, which says X=π−X = \pi^{-}. □\square

Termination. The chain of J3 stops after at most nn steps, as shown above. The loop on mm has nn iterations.

Cost. The loop of J3 has tmt_m runs for the name mm, and the total A=∑mtmA = \sum_m t_m is the unknown. The rest of the work is a constant for each name. Program J has the exact time, and the average of AA is derived below.

Program (MIX program for Algorithm J, TAOCP Program 1.3.3J). The first loop negates the nn entries with a store of the sign field only. The second loop is the main loop on mm (in rI1). The chain loop of J3 has three instructions: a negation of the pointer, a load of the next entry with the sign reversed, and a test of the sign. The final part of the body of the main loop has three transfers (load, store, store) and the loop control.

Node: Program 1.3.3J · Lean: not yet stated

The groups and the time. The setup and the negation loop take 4n+14n + 1 units. The main loop has one setup (1u1u, once), a head (1u1u for each mm), the chain loop (4u4u for each run, AA runs in all), a body of load, store, store (6u6u for each mm) and a loop control (2u2u for each mm). So

TJ=(13n+4A+2)u.T_J = (13n + 4A + 2)u.

Example. For π=[4,7,3,1,2,5,6]\pi = [4, 7, 3, 1, 2, 5, 6], n=7n = 7 and A=14A = 14, so TJ=91+56+2=149uT_J = 91 + 56 + 2 = 149u. A MIX simulator gave 149u149u before the halt. On the same 300 random permutations as for Program I, the array became the inverse and the time was exactly 13n+4A+213n + 4A + 2, with AA counted by the simulator.

Proof. The negation loop takes (1+4n)u(1 + 4n)u: 1u1u to set the index, and for each entry 4u4u for its three instructions (a store of the sign, 2u2u, an increment and a jump, 1u1u each). The main loop adds 1+n⋅(1+6+2)+4A1 + n \cdot (1 + 6 + 2) + 4A. The sum is 13n+4A+213n + 4A + 2. □\square

Analysis (the running time of Programs I and J, TAOCP exercise 1.3.3-14 and the text). With CC the number of cycles, the time of Program I is (14n+C+2)u(14n + C + 2)u, and the time of Program J is (13n+4A+2)u(13n + 4A + 2)u. For a random permutation, the average of CC is HnH_n, and the average of AA is (n+1)Hn−n(n + 1)H_n - n. So the average times are

14n+Hn+2and9n+4(n+1)Hn+2.14n + H_n + 2 \qquad\text{and}\qquad 9n + 4(n + 1)H_n + 2.

Node: 1.3.3-anal-progIJ · Lean: not yet stated

Explanation. Program I runs in time that is linear in nn on average (and in the worst case, as C≤nC \le n). Program J has a term in nln⁡nn \ln n, because the chain of the name mm has average length about n/mn/m, and the sum of n/mn/m is nHnn H_n. Program J has the shorter loop body, but the chains are costly for large nn.

Example. The average times for several nn are:

nn Program I Program J J / I
10 144.93 220.87 1.52
100 1407.19 2997.70 2.13
1000 14009.49 38973.83 2.78
10000 140011.79 481545.39 3.44

For n=4n = 4 the exact average of AA is 77/1277/12, found by running Algorithm J on all 2424 permutations. The formula gives 5H4−4=5⋅25/12−4=77/125 H_4 - 4 = 5 \cdot 25/12 - 4 = 77/12. The exact averages for n=1,…,7n = 1, \ldots, 7 from the complete enumeration are 1,5/2,13/3,77/12,87/10,223/20,481/351, 5/2, 13/3, 77/12, 87/10, 223/20, 481/35, and they equal (n+1)Hn−n(n + 1)H_n - n.

Proof. The count for Program I is proved above, and the mean of CC is HnH_n by eq. (21) below. For AA: the name mm costs tmt_m runs of J3, and tm=min⁡{t≥1:ψt(m)≤m}t_m = \min\{t \ge 1 : \psi^t(m) \le m\} (the chain stops at the first j=ψt−1(m)j = \psi^{t-1}(m) with ψ(j)≤m\psi(j) \le m, because ψ(j)∈D\psi(j) \in D means ψ(j)>m\psi(j) > m). For a uniform random π\pi, ψ\psi is uniform. The event tm>rt_m > r means that ψ(m),ψ2(m),…,ψr(m)\psi(m), \psi^2(m), \ldots, \psi^r(m) all exceed mm. These values are distinct (a repeat would need ψs(m)=m\psi^s(m) = m, which is not greater than mm), and they are rr names among the n−mn - m names above mm. The number of such ψ\psi is (n−m)r‾(n−r)!(n - m)^{\underline r}(n - r)!: choose the ordered values, then complete the partial injection. So P(tm>r)=(n−m)r‾/nr‾P(t_m > r) = (n - m)^{\underline r}/n^{\underline r}, which equals (n−mr)/(nr)\binom{n-m}{r}/\binom{n}{r}. Put q=n−mq = n - m. Then E[tm]=∑r≥0P(tm>r)=∑r=0q(qr)(nr).E[t_m] = \sum_{r \ge 0} P(t_m > r) = \sum_{r=0}^{q} \frac{\binom{q}{r}}{\binom{n}{r}}. Use (qr)(nq)=(nr)(n−rq−r)\binom{q}{r}\binom{n}{q} = \binom{n}{r}\binom{n-r}{q-r} (both sides equal n!/(r! (q−r)! (n−q)!)n!/(r!\,(q-r)!\,(n-q)!)). The sum becomes (nq)−1∑r=0q(n−rq−r)\binom{n}{q}^{-1}\sum_{r=0}^{q}\binom{n-r}{q-r}. With s=q−rs = q - r the sum is ∑s=0q(n−q+ss)=(n+1q)\sum_{s=0}^{q}\binom{n-q+s}{s} = \binom{n+1}{q} (parallel summation, eq. 1.2.6(10)). So E[tm]=(n+1q)/(nq)=(n+1)/(n+1−q)=(n+1)/(m+1)E[t_m] = \binom{n+1}{q}/\binom{n}{q} = (n+1)/(n+1-q) = (n+1)/(m+1). Then E[A]=(n+1)∑m=1n1/(m+1)=(n+1)(Hn+1−1)=(n+1)Hn−nE[A] = (n+1)\sum_{m=1}^{n} 1/(m+1) = (n+1)(H_{n+1} - 1) = (n+1)H_n - n. Insert in TJT_J: 13n+4(n+1)Hn−4n+2=9n+4(n+1)Hn+213n + 4(n+1)H_n - 4n + 2 = 9n + 4(n+1)H_n + 2. □\square

Definition (canonical cycle form, TAOCP eq. 1.3.3(20)). The canonical cycle form of a permutation lists all cycles, the singletons included. Inside each cycle, the smallest name is written first. The cycles are written in decreasing order of their first names. Write a permutation of {1,…,n}\{1, \ldots, n\} in this form and delete the parentheses. The result is a linear arrangement of {1,…,n}\{1, \ldots, n\}, and the map from permutations in cycle form to arrangements is a bijection. The cycles of the permutation correspond to the left-to-right minima of the arrangement.

Node: 1.3.3-(20) · Lean: not yet stated

Explanation. A left-to-right minimum of an arrangement is an entry that is smaller than all entries before it (the first entry is always one). In a canonical form the first name of each cycle is smaller than all names of the earlier cycles and of its own cycle, so it is a left-to-right minimum. The other names of a cycle are larger than the first name of their own cycle, and that name stands before them, so they are not minima. To go back, put a "(" before each left-to-right minimum and a ")" before each "(" except the first, and at the end.

Example. Take (6 2 5)(3)(1 7 4)(6\,2\,5)(3)(1\,7\,4). Rotate each cycle so that the smallest name comes first: (2 5 6)(3)(1 7 4)(2\,5\,6)(3)(1\,7\,4). Sort the cycles by decreasing first name (3,2,13, 2, 1): (3)(2 5 6)(1 7 4)(3)(2\,5\,6)(1\,7\,4). Delete the parentheses: 3 2 5 6 1 7 43\,2\,5\,6\,1\,7\,4. The left-to-right minima of this arrangement are 3,2,13, 2, 1: three cycles. To go back from 3 2 5 6 1 7 43\,2\,5\,6\,1\,7\,4, put "(" before 33, 22 and 11 and get (3)(2 5 6)(1 7 4)(3)(2\,5\,6)(1\,7\,4). A second example reads an arrangement as a permutation again: the arrangement 4 6 7 2 1 3 54\,6\,7\,2\,1\,3\,5 has minima 4,2,14, 2, 1, so it comes from (4 6 7)(2)(1 3 5)(4\,6\,7)(2)(1\,3\,5). As a permutation of {1,…,7}\{1, \ldots, 7\} (X[1]=4X[1] = 4, X[2]=6X[2] = 6, and so on) it has the cycle form (1 4 2 6 3 7 5)(1\,4\,2\,6\,3\,7\,5).

Proof. Let π\pi be written in canonical form. Take the first name ff of a cycle. Every name before it belongs to an earlier cycle. In an earlier cycle with first name f′f', the name f′f' is the smallest of its cycle, and f′>ff' > f by the order of the cycles, so every name of the earlier cycle exceeds ff. Hence ff is a left-to-right minimum. A name yy that is not first in its cycle is larger than the first name of its cycle, which stands before it, so yy is not a minimum. Hence the minima are exactly the first names, and the cycles can be recovered by cutting before each minimum. Conversely, take any arrangement and cut it before each minimum. Inside a piece, the first name is the running minimum and all other names are larger than it, so the first name is the smallest of the piece. The first names of the pieces decrease from left to right because each is a new running minimum. So the pieces form a canonical cycle form. The two maps are inverse to each other, so the correspondence is a bijection between the n!n! permutations and the n!n! arrangements. □\square

Theorem (the number of cycles of a random permutation, TAOCP eq. 1.3.3(21)). The number of cycles of a permutation of nn names (singletons counted) has the minimum 11, the maximum nn, the mean HnH_n and the variance Hn−Hn(2)H_n - H_n^{(2)}, where Hn(2)=∑r≤nr−2H_n^{(2)} = \sum_{r \le n} r^{-2}. The number of permutations with kk cycles is the Stirling number of the first kind [nk]\left[{n \atop k}\right], and ∑k[nk]zk=z(z+1)⋯(z+n−1)\sum_k \left[{n \atop k}\right] z^k = z(z + 1)\cdots(z + n - 1).

Node: 1.3.3-(21) · Lean: not yet stated

Explanation. By the bijection of (20), the number of cycles is the number of left-to-right minima of a random arrangement. Section 1.2.10 has the same statistic for the right-to-left maxima. The answer is a sum of nn independent random variables: the rr-th is 11 with probability 1/r1/r and 00 otherwise. So the mean is ∑1/r\sum 1/r, and the variance is ∑(1/r)(1−1/r)\sum (1/r)(1 - 1/r). The number of cycles has no large spread: its deviation is about ln⁡n\sqrt{\ln n}.

Example. The counts by exhaustive enumeration are:

nn k=1k = 1 22 33 44 55 66 mean variance
3 2 3 1 11/611/6 17/3617/36
4 6 11 6 1 25/1225/12 95/14495/144
5 24 50 35 10 1 137/60137/60 2951/36002951/3600
6 120 274 225 85 15 1 49/2049/20 3451/36003451/3600

For n=4n = 4, H4=25/12H_4 = 25/12 and H4−H4(2)=25/12−205/144=95/144H_4 - H_4^{(2)} = 25/12 - 205/144 = 95/144. The total number of cycles of the 24 permutations of 4 names is 6⋅1+11⋅2+6⋅3+1⋅4=50=24⋅25/126 \cdot 1 + 11 \cdot 2 + 6 \cdot 3 + 1 \cdot 4 = 50 = 24 \cdot 25/12, which equals n!Hnn!H_n.

Proof. Let c(n,k)c(n, k) be the number of arrangements of {1,…,n}\{1, \ldots, n\} with kk left-to-right minima. Build an arrangement of nn names from one of n−1n - 1 names by putting the name nn in one of the nn places. The name nn is a minimum only at the front, because it exceeds every other name. A name that is not nn keeps its status (it is a minimum or not) when nn is inserted, because nn is larger than all names and does not change any running minimum. So the front insertion gives k+1k + 1 minima from kk, and each of the other n−1n - 1 insertions keeps kk. Hence c(n,k)=c(n−1,k−1)+(n−1)c(n−1,k)c(n, k) = c(n - 1, k - 1) + (n - 1)c(n - 1, k), with c(1,1)=1c(1, 1) = 1. By the bijection of (20) the number of permutations with kk cycles obeys the same recurrence, which is the recurrence of the Stirling numbers of the first kind. For the generating function gn(z)=∑kc(n,k)zkg_n(z) = \sum_k c(n, k)z^k the recurrence says gn=(z+n−1)gn−1g_n = (z + n - 1)g_{n-1} and g1=zg_1 = z, so gn(z)=z(z+1)⋯(z+n−1)g_n(z) = z(z + 1)\cdots(z + n - 1). Dividing by n!n!, the probability generating function is ∏r=1nz+r−1r\prod_{r=1}^{n} \frac{z + r - 1}{r}. The factor r−1r+1rz\frac{r - 1}{r} + \frac{1}{r}z is the generating function of a variable that is 11 with probability 1/r1/r and 00 otherwise. The mean of such a variable is 1/r1/r and its variance is 1r(1−1r)\frac{1}{r}\left(1 - \frac{1}{r}\right). The product of generating functions is the generating function of the sum of independent variables, and means and variances add. So the mean is ∑r≤n1/r=Hn\sum_{r \le n} 1/r = H_n and the variance is ∑r≤n(1/r−1/r2)=Hn−Hn(2)\sum_{r \le n}(1/r - 1/r^2) = H_n - H_n^{(2)}. The minimum is 11 (the arrangement 1 2…n1\,2 \ldots n has the one minimum 11, and every arrangement has at least the first entry as a minimum) and the maximum is nn (the arrangement n…2 1n \ldots 2\,1). □\square

Definition (permutations with exactly kk fixed names, TAOCP eq. 1.3.3(22)). For 0≤k≤n0 \le k \le n, the symbol PnkP_{nk} counts the permutations of nn names with exactly kk singleton cycles, that is, kk fixed names. The number Pm0P_{m0} is the number of derangements of mm names. Then

Pnk=(nk)Pn−k,0.P_{nk} = \binom{n}{k} P_{n-k,0}.

Node: 1.3.3-(22) · Lean: not yet stated

Explanation. A permutation with exactly kk fixed names is made in two steps. Choose the kk names that stay fixed. Then permute the other n−kn - k names with no fixed name.

Example. The counts PnkP_{nk} for k=0,…,nk = 0, \ldots, n are (by exhaustive enumeration) n=5n = 5: 44,45,20,10,0,144, 45, 20, 10, 0, 1; n=6n = 6: 265,264,135,40,15,0,1265, 264, 135, 40, 15, 0, 1. Check P51=(51)P40=5⋅9=45P_{51} = \binom{5}{1}P_{40} = 5 \cdot 9 = 45 and P62=(62)P40=15⋅9=135P_{62} = \binom{6}{2}P_{40} = 15 \cdot 9 = 135.

Proof. A permutation with exactly the fixed set KK (∣K∣=k|K| = k) is the identity on KK and a permutation with no fixed name on the rest. The map that restricts the permutation to the rest is a bijection from the permutations with fixed set KK to the permutations of the n−kn - k other names with no fixed name. There are (nk)\binom{n}{k} sets KK and each gives Pn−k,0P_{n-k,0} permutations. The sets KK are different, so the permutations that they give are different. □\square

Equation (the sum rule, TAOCP eq. 1.3.3(23)). Every permutation has some number of fixed names, so

n!=Pnn+Pn,n−1+Pn,n−2+⋯+Pn0.n! = P_{nn} + P_{n,n-1} + P_{n,n-2} + \cdots + P_{n0}.

Node: 1.3.3-(23) · Lean: not yet stated

Explanation. The n!n! permutations are sorted by their number of fixed names. Note that Pn,n−1=0P_{n,n-1} = 0 for n≥1n \ge 1, because n−1n - 1 fixed names force the last name to be fixed too.

Example. For n=5n = 5: 1+0+10+20+45+44=1201 + 0 + 10 + 20 + 45 + 44 = 120. For n=6n = 6: 1+0+15+40+135+264+265=7201 + 0 + 15 + 40 + 135 + 264 + 265 = 720.

Proof. Each permutation has exactly one number kk of fixed names, so it is counted in exactly one PnkP_{nk}. □\square

Equation (the derangement identity, TAOCP eq. 1.3.3(24)). Put Dm=Pm0D_m = P_{m0}. Then for every n≥0n \ge 0,

n!=∑m=0n(nm)Dm=D0+nD1+n(n−1)2!D2+⋯+Dn.n! = \sum_{m=0}^{n} \binom{n}{m} D_m = D_0 + nD_1 + \frac{n(n-1)}{2!}D_2 + \cdots + D_n.

Node: 1.3.3-(24) · Lean: not yet stated

Explanation. This is eq. (23) after the substitution of eq. (22): Pnk=(nk)Dn−kP_{nk} = \binom{n}{k}D_{n-k}, and (nk)=(nn−k)\binom{n}{k} = \binom{n}{n-k}. Written with falling powers, n!=∑mnm‾Dm/m!n! = \sum_m n^{\underline m}D_m/m!.

Example. With D0,…,D5=1,0,1,2,9,44D_0, \ldots, D_5 = 1, 0, 1, 2, 9, 44: for n=5n = 5, 1+5⋅0+10⋅1+10⋅2+5⋅9+44=1+0+10+20+45+44=1201 + 5 \cdot 0 + 10 \cdot 1 + 10 \cdot 2 + 5 \cdot 9 + 44 = 1 + 0 + 10 + 20 + 45 + 44 = 120.

Proof. In (23), put m=n−km = n - k and use Pn,n−m=(nn−m)Dm=(nm)DmP_{n,n-m} = \binom{n}{n-m}D_m = \binom{n}{m}D_m. □\square

Equation (the number of derangements, TAOCP eq. 1.3.3(25)). For every m≥0m \ge 0,

Dmm!=1−11!+12!−⋯+(−1)mm!.\frac{D_m}{m!} = 1 - \frac{1}{1!} + \frac{1}{2!} - \cdots + \frac{(-1)^m}{m!}.

Node: 1.3.3-(25) · Lean: not yet stated

Explanation. The probability that a random permutation of mm names has no fixed name is a partial sum of the series for e−1e^{-1}. It converges to 1/e≈0.36791/e \approx 0.3679 very fast: the error after mm terms is less than 1/(m+1)!1/(m+1)!.

Example. DmD_m for m=0,…,9m = 0, \ldots, 9 is 1,0,1,2,9,44,265,1854,14833,1334961, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496. Check: 9!(1−1+1/2−1/6+1/24−1/120+1/720−1/5040+1/40320−1/362880)=362880−362880+181440−60480+15120−3024+504−72+9−1=1334969!(1 - 1 + 1/2 - 1/6 + 1/24 - 1/120 + 1/720 - 1/5040 + 1/40320 - 1/362880) = 362880 - 362880 + 181440 - 60480 + 15120 - 3024 + 504 - 72 + 9 - 1 = 133496.

Proof. Identity (24) determines the numbers DnD_n one after the other: the term m=nm = n is DnD_n and the other terms involve only DmD_m with m<nm < n. So there is at most one sequence that satisfies (24) for all nn, and it is enough to check that dm=m!∑l≤m(−1)l/l!d_m = m!\sum_{l \le m}(-1)^l/l! satisfies it. Compute ∑m=0n(nm)dm=n!∑m=0n1(n−m)!∑l=0m(−1)ll!\sum_{m=0}^{n}\binom{n}{m}d_m = n!\sum_{m=0}^{n}\frac{1}{(n-m)!}\sum_{l=0}^{m}\frac{(-1)^l}{l!}, because (nm)m!=n!/(n−m)!\binom{n}{m}m! = n!/(n-m)!. Put s=n−ms = n - m. The double sum runs over pairs (s,l)(s, l) with s+l≤ns + l \le n and has the terms (−1)ls! l!\frac{(-1)^l}{s!\,l!}. Group by t=s+lt = s + l: 1s! l!=1t!(tl)\frac{1}{s!\,l!} = \frac{1}{t!}\binom{t}{l}. So the sum is ∑t=0n1t!∑l=0t(−1)l(tl)\sum_{t=0}^{n}\frac{1}{t!}\sum_{l=0}^{t}(-1)^l\binom{t}{l}. The inner sum is (1−1)t(1 - 1)^t, which is 11 for t=0t = 0 and 00 for t≥1t \ge 1. So the double sum is 11 and the whole is n!n!. Hence dm=Dmd_m = D_m. □\square

Equation (the distribution of the fixed names, TAOCP eq. 1.3.3(26)). The probability that a random permutation of nn names has exactly kk fixed names is

pnk=Pnkn!=1k!(1−11!+⋯+(−1)n−k(n−k)!).p_{nk} = \frac{P_{nk}}{n!} = \frac{1}{k!}\left(1 - \frac{1}{1!} + \cdots + \frac{(-1)^{n-k}}{(n-k)!}\right).

Node: 1.3.3-(26) · Lean: not yet stated

Explanation. For fixed kk and large nn, pnk→e−1/k!p_{nk} \to e^{-1}/k!, the Poisson distribution with mean 11.

Example. For n=5n = 5: p50=44/120=11/30p_{50} = 44/120 = 11/30, p51=45/120=3/8p_{51} = 45/120 = 3/8, p52=20/120=1/6p_{52} = 20/120 = 1/6, p53=10/120=1/12p_{53} = 10/120 = 1/12, p54=0p_{54} = 0, p55=1/120p_{55} = 1/120. The formula gives for k=1k = 1: 1−1+1/2−1/6+1/24=3/81 - 1 + 1/2 - 1/6 + 1/24 = 3/8, and for k=2k = 2: 12(1−1+1/2−1/6)=1/6\frac{1}{2}(1 - 1 + 1/2 - 1/6) = 1/6.

Proof. By (22), pnk=(nk)Dn−k/n!=1k!Dn−k(n−k)!p_{nk} = \binom{n}{k}D_{n-k}/n! = \frac{1}{k!}\frac{D_{n-k}}{(n-k)!}, and by (25) the last fraction is the partial sum. □\square

Equation (the generating function of the fixed names, TAOCP eq. 1.3.3(27)). The generating function Gn(z)=∑kpnkzkG_n(z) = \sum_k p_{nk}z^k is

Gn(z)=∑j=0n(z−1)jj!.G_n(z) = \sum_{j=0}^{n}\frac{(z - 1)^j}{j!}.

Node: 1.3.3-(27) · Lean: not yet stated

Explanation. The sum is the start of the series of ez−1e^{z-1}, which is the generating function of the Poisson distribution with mean 11.

Example. G2(z)=1+(z−1)+(z−1)2/2=12+z22G_2(z) = 1 + (z - 1) + (z - 1)^2/2 = \frac{1}{2} + \frac{z^2}{2}. This says that of the two permutations of two names, one has no fixed name (probability 1/21/2) and one has two (probability 1/21/2), which is right. G3(z)=G2(z)+(z−1)3/6=13+z2+z36G_3(z) = G_2(z) + (z - 1)^3/6 = \frac{1}{3} + \frac{z}{2} + \frac{z^3}{6}, so p30=1/3p_{30} = 1/3, p31=1/2p_{31} = 1/2, p32=0p_{32} = 0, p33=1/6p_{33} = 1/6 (the counts 2,3,0,12, 3, 0, 1 of 6).

Proof. Expand (z−1)j/j!=∑k≤jzkk!(−1)j−k(j−k)!(z - 1)^j/j! = \sum_{k \le j}\frac{z^k}{k!}\frac{(-1)^{j-k}}{(j-k)!} (the binomial theorem and (jk)/j!=1/(k!(j−k)!)\binom{j}{k}/j! = 1/(k!(j-k)!)). Sum over j≤nj \le n. The coefficient of zkz^k is 1k!∑j=kn(−1)j−k(j−k)!\frac{1}{k!}\sum_{j=k}^{n}\frac{(-1)^{j-k}}{(j-k)!}. With l=j−kl = j - k it is 1k!∑l=0n−k(−1)ll!\frac{1}{k!}\sum_{l=0}^{n-k}\frac{(-1)^l}{l!}, which is pnkp_{nk} by (26). □\square

Equation (the statistics of the fixed names, TAOCP eq. 1.3.3(28)). For n≥2n \ge 2, the number of fixed names has the minimum 00, the mean 11, the maximum nn and the variance 11 (deviation 11). For n=1n = 1 the mean is 11 and the variance is 00.

Node: 1.3.3-(28) · Lean: not yet stated

Explanation. The mean and the variance do not depend on nn for n≥2n \ge 2. A random permutation has one fixed name on average, whatever its size.

Example. For n=5n = 5: the counts are 44,45,20,10,0,144, 45, 20, 10, 0, 1 for k=0,…,5k = 0, \ldots, 5. The mean is (45+40+30+0+5)/120=1(45 + 40 + 30 + 0 + 5)/120 = 1. The second moment is (45+80+90+0+25)/120=2(45 + 80 + 90 + 0 + 25)/120 = 2, so the variance is 2−1=12 - 1 = 1. For n=6n = 6 the same computation from the counts of eq. (22) gives mean 11 and variance 11.

Proof. From (27), Gn′(z)=∑j=1n(z−1)j−1(j−1)!=Gn−1(z)G_n'(z) = \sum_{j=1}^{n}\frac{(z-1)^{j-1}}{(j-1)!} = G_{n-1}(z). The generating function of a probability distribution has G(1)=1G(1) = 1, G′(1)=G'(1) = the mean and G′′(1)=E[K(K−1)]G''(1) = E[K(K-1)]. Hence Gn(1)=1G_n(1) = 1, the mean is Gn′(1)=Gn−1(1)=1G_n'(1) = G_{n-1}(1) = 1 for n≥1n \ge 1, and Gn′′(1)=Gn−1′(1)=Gn−2(1)=1G_n''(1) = G_{n-1}'(1) = G_{n-2}(1) = 1 for n≥2n \ge 2. So E[K2]=Gn′′(1)+Gn′(1)=2E[K^2] = G_n''(1) + G_n'(1) = 2 and the variance is 2−1=12 - 1 = 1. For n=1n = 1, G1′′(1)=G0′(1)=0G_1''(1) = G_0'(1) = 0, since G0=1G_0 = 1, so E[K2]=1E[K^2] = 1 and the variance is 00. The minimum is 00 for n≥2n \ge 2, because Dn>0D_n > 0 (by (25), Dn/n!>0D_n/n! > 0, as the partial sums of the alternating series with decreasing terms are positive for n≥2n \ge 2; the example (1 2…n)(1\,2 \ldots n) is a derangement). The maximum is nn (the identity). □\square

Theorem (the principle of inclusion and exclusion, TAOCP eq. 1.3.3(29)). Let S1,…,SMS_1, \ldots, S_M be subsets of a set of NN elements. The number of elements that lie in none of the sets is

N−∑j∣Sj∣+∑j<k∣Sj∩Sk∣−∑i<j<k∣Si∩Sj∩Sk∣+⋯+(−1)M∣S1∩⋯∩SM∣.N - \sum_{j}|S_j| + \sum_{j<k}|S_j \cap S_k| - \sum_{i<j<k}|S_i \cap S_j \cap S_k| + \cdots + (-1)^M|S_1 \cap \cdots \cap S_M|.

Node: 1.3.3-(29) · Lean: not yet stated

Explanation. The first sum removes the elements in a set, but it removes twice the elements that lie in two sets. The second sum puts these back, and so on. Each term of the series adds or removes the elements that lie in a given number of sets.

Example. Count the permutations of {1,2,3}\{1, 2, 3\} with no fixed name. Let SjS_j be the set of permutations that fix jj. Then N=6N = 6, ∣Sj∣=2|S_j| = 2 (three sets), ∣Sj∩Sk∣=1|S_j \cap S_k| = 1 (three pairs), ∣S1∩S2∩S3∣=1|S_1 \cap S_2 \cap S_3| = 1. The count is 6−3⋅2+3⋅1−1=26 - 3 \cdot 2 + 3 \cdot 1 - 1 = 2, the two derangements (1 2 3)(1\,2\,3) and (1 3 2)(1\,3\,2). In general, ∣Sj1∩⋯∩Sjk∣=(n−k)!|S_{j_1} \cap \cdots \cap S_{j_k}| = (n - k)! and there are (nk)\binom{n}{k} choices, so the number of derangements is ∑k(−1)k(nk)(n−k)!=n!∑k(−1)k/k!\sum_k(-1)^k\binom{n}{k}(n - k)! = n!\sum_k(-1)^k/k!, in agreement with (25).

Proof. Take an element xx that lies in exactly rr of the sets. It is counted once in NN. It is counted (rk)\binom{r}{k} times in the sum of the intersections of kk sets, because it lies in exactly the intersections of kk sets chosen among its rr sets. So the total contribution of xx is ∑k=0r(−1)k(rk)=(1−1)r\sum_{k=0}^{r}(-1)^k\binom{r}{k} = (1 - 1)^r, which is 11 for r=0r = 0 and 00 for r≥1r \ge 1. So the sum counts the elements with r=0r = 0 once, and no other element. □\square

The exercises

The table has the exercises of Section 1.3.3. The kind is the class of spec 06.3 that C1 proposes, and the indexer of S0 fixes it in the map.

Exercise Rating Markers Kind Lean Solution
1.3.3-1 2 K3 not yet stated X1, 1.3.3-1
1.3.3-2 10 K5 not yet stated X1, 1.3.3-2
1.3.3-3 3 K3 not yet stated X1, 1.3.3-3
1.3.3-4 10 K3 not yet stated X1, 1.3.3-4
1.3.3-5 10 M K3 not yet stated X1, 1.3.3-5
1.3.3-6 28 M K7 not yet stated X1, 1.3.3-6
1.3.3-7 10 K3 not yet stated X1, 1.3.3-7
1.3.3-8 23 K2 not yet stated X1, 1.3.3-8
1.3.3-9 10 K2 not yet stated X1, 1.3.3-9
1.3.3-10 28 M K7 not yet stated X1, 1.3.3-10
1.3.3-11 15 K5 not yet stated X1, 1.3.3-11
1.3.3-12 27 M K5 not yet stated X1, 1.3.3-12
1.3.3-13 24 M K1 not yet stated X1, 1.3.3-13
1.3.3-14 34 M K7 not yet stated X1, 1.3.3-14
1.3.3-15 12 M K3 not yet stated X1, 1.3.3-15
1.3.3-16 15 M K3 not yet stated X1, 1.3.3-16
1.3.3-17 24 M K1 not yet stated X1, 1.3.3-17
1.3.3-18 27 M K3 not yet stated X1, 1.3.3-18
1.3.3-19 21 HM K1 not yet stated X1, 1.3.3-19
1.3.3-20 20 M K3 not yet stated X1, 1.3.3-20
1.3.3-21 22 M K3 not yet stated X1, 1.3.3-21
1.3.3-22 34 HM K1 not yet stated X1, 1.3.3-22
1.3.3-23 42 HM K7 not yet stated X1, 1.3.3-23
1.3.3-24 41 M K7 not yet stated X1, 1.3.3-24
1.3.3-25 22 M K1 not yet stated X1, 1.3.3-25
1.3.3-26 24 M K3 not yet stated X1, 1.3.3-26
1.3.3-27 20 M K3 not yet stated X1, 1.3.3-27
1.3.3-28 21 M K3 not yet stated X1, 1.3.3-28
1.3.3-29 25 M K1 not yet stated X1, 1.3.3-29
1.3.3-30 24 M K3 not yet stated X1, 1.3.3-30
1.3.3-31 38 HM K1 not yet stated X1, 1.3.3-31
1.3.3-32 25 M K3 not yet stated X1, 1.3.3-32
1.3.3-33 33 M K1 not yet stated X1, 1.3.3-33
1.3.3-34 25 M K5 not yet stated X1, 1.3.3-34
1.3.3-35 30 M K5 not yet stated X1, 1.3.3-35
1.3.3-36 27 K6 not yet stated X1, 1.3.3-36
1.3.3-37 26 M K1 not yet stated X1, 1.3.3-37

The order to do them: 1.3.3-1 to 5 first, to get used to cycle form and the product (exercise 2 does a rearrangement with exchanges instead of assignments). Exercises 1.3.3-6 and 7 train the cost analysis of Program A, and 1.3.3-10 does the same for Program B; the analysis of Program B above gives its formula. Exercises 1.3.3-8 and 9 compare Algorithms A and B: whether B can read from the left, and whether the two outputs agree exactly. Exercise 1.3.3-11 asks for the rule that inverts a permutation in cycle form, and 1.3.3-12 transposes a rectangular matrix in place. Exercise 1.3.3-13 is the proof of Algorithm J, which the chapter gives in full, 1.3.3-14 is the average of AA, and 1.3.3-24 asks for its variance. Exercises 1.3.3-15 and 16 use the canonical form. Exercises 1.3.3-17 to 23 go further into the statistics of cycles and fixed names. Exercises 1.3.3-25 to 27 treat inclusion and exclusion. Exercises 1.3.3-28 to 31 study the Josephus permutation in cycle form, 1.3.3-32 and 33 build permutations from products of transpositions and of fixed sequences, 1.3.3-34 to 36 move blocks of data in place, and 1.3.3-37 is about even permutations.

Lean

The Lean code of tamnd/taocp-lean at main has no declaration for the algorithms and programs of Section 1.3.3, so each Node line of this chapter says "not yet stated". Mathlib has the following objects.

  • Permutations: Equiv.Perm with Equiv.Perm.one_apply and Equiv.Perm.inv_def. The theorem Equiv.Perm.mul_apply gives (στ)(x)=σ(τ(x))(\sigma\tau)(x) = \sigma(\tau(x)), so the product of Mathlib acts from right to left. The product of this chapter acts from left to right, so a Lean form of eq. 1.3.3(1) to (6) swaps the factors.
  • Cycles: Equiv.Perm.cycleType records the cycles of length at least two, and Equiv.Perm.cycleType_eq_zero says that it is empty for the identity only. Equiv.Perm.sum_cycleType gives the sum of the lengths, Equiv.Perm.cycleOf the cycle through a point and Equiv.Perm.SameCycle the relation of lying in one cycle. Equiv.Perm.card_fixedPoints counts the fixed points.
  • Derangements: derangements, mem_derangements_iff_fixedPoints_eq_empty, numDerangements, numDerangements_add_two, numDerangements_succ, numDerangements_sum, card_derangements_eq_numDerangements and card_derangements_fin_eq_numDerangements. They cover eq. 1.3.3(24) and (25).
  • Stirling numbers: Nat.stirlingFirst and Nat.stirlingFirst_succ_succ in Mathlib, and TAOCP.stirling1, TAOCP.stirling1_succ_succ and TAOCP.harmonicPow in taocp-lean. Mathlib has no theorem that counts the permutations of nn points by their number of cycles, so eq. 1.3.3(21) has no Lean form yet.
  • Inclusion and exclusion: Finset.inclusion_exclusion_card_biUnion and Finset.inclusion_exclusion_card_inf_compl for eq. 1.3.3(29), and harmonic for HnH_n.

Notes and history

Cycle notation and the product of permutations are older than the machine algorithms of this section. The section uses them to show how a program can work on symbolic data with one pass or with a table. The two algorithms trade time for space: Algorithm A needs no table and runs in time proportional to the square of the input size in the worst case, and Algorithm B needs a table and runs faster.

The inverse in place has a long literature. The book credits Algorithm I to B.-C. Huang (1981) and Algorithm J to J. Boothroyd. The analysis of the chain length of Algorithm J gives (n+1)Hn−n(n+1)H_n - n, a case where a harmonic number appears from a simple expected value.

The numbers [nk]\left[{n \atop k}\right] are named after J. Stirling, who studied them in the Methodus differentialis (1730). Inclusion and exclusion appears in the Doctrine of Chances of A. de Moivre (1718). The matching problem, which asks for the chance that a permutation has no fixed point, was studied by P. R. de Montmort a few years earlier.

Section 1.3.3 of TAOCP uses permutations as the subject of four MIX programs and as the subject of two short analyses. It first shows how to write a permutation as a set of cycles and how to multiply two permutations. It then gives two algorithms that turn a product of cycles into disjoint cycles, one that scans the input many times and one that scans it once, and a MIX program for each. Then it builds two algorithms that invert a permutation inside its own array, again with a MIX program for each. It ends with the statistics of random permutations: the number of cycles has the mean HnH_n, and the number of fixed points has mean 11 and variance 11. This chapter of C1 explains each item of the section, proves each claim in full, and checks each count and each time on a small input that C1 runs.

The source of this page. Something is wrong? Report it.