Module contents
Lesson 11 of 22Core 100 min

Permutations: cycle structure, parity and counting under symmetry

Permutations as objects: cycles, composition, sign and the symmetric group. Group actions and Burnside's lemma count configurations up to symmetry, as in AlphaGo Zero's board-symmetry data augmentation. Fisher–Yates shuffling is proved correct.

After this lesson you can

  • Compose, invert and decompose permutations into disjoint cycles
  • Prove sign is well-defined and calculate it by cycles or inversions
  • Calculate orbits and stabilizers and apply Burnside's lemma
  • Use parity invariants to prove impossibility in the 15-puzzle
  • Prove Fisher–Yates yields uniform permutations and naive shuffling does not

Before you start

Motivation: three problems with the same structure

Three situations arise when training real models:

  • Shuffling data. At each epoch’s start the training set is reordered (epochs and shuffling). If nonuniform, some examples tend toward the epoch’s start and others its end, with bias invisible in the loss curve. Writing a correct shuffle is easy; writing one that looks correct but is not is easier.
  • Board symmetries. A Go position rotated 90° is the same for game purposes. AlphaGo Zero used the board’s 8 symmetries to multiply training data by 8 (Silver et al., 2017). How many genuinely distinct positions remain? It is not the total divided by 8.
  • Determinant sign. The Leibniz formula for the determinant, det⁡A=∑σsgn⁡(σ)∏iaiσ(i)\det\mat{A} = \sum_{\sigma} \operatorname{sgn}(\sigma)\prod_i a_{i\sigma(i)}, sums over all column reorderings, each with sign ±1\pm 1. Why is that sign well-defined?

All three concern the same object: permutations, reorderings of a finite set, and actions of a permutation group on other objects. This lesson studies their mathematical structure: cycle decomposition, sign, algebraic structure, counting configurations up to symmetry with Burnside’s lemma, why parity makes Sam Loyd’s 15-puzzle impossible, and why Fisher–Yates shuffling is uniform while the naive version is not.

Permutations as bijections

Three common notations are worth mastering:

  • Two-line notation: elements above and their images below. For our 7-element permutation,
σ=(12345674176523).\sigma = \begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 4 & 1 & 7 & 6 & 5 & 2 & 3 \end{pmatrix}.
  • One-line notation: only the bottom row, σ=4 1 7 6 5 2 3\sigma = 4\,1\,7\,6\,5\,2\,3. A program stores an array p with p[i] = σ(i).
  • Cycle notation: follow arrows 1→4→6→2→11 \to 4 \to 6 \to 2 \to 1 and 3→7→33 \to 7 \to 3, with 5 fixed, writing σ=(1 4 6 2)(3 7)\sigma = (1\,4\,6\,2)(3\,7). Developed next.

There are n!n! permutations of [n][n]: choose σ(1)\sigma(1) among nn values, σ(2)\sigma(2) among the remaining n−1n-1, and so on (product rule, already used to count permutations as orderings). Here the viewpoint changes: a permutation σ\sigma is a function, and functions compose.

Composition. As elsewhere in mathematics, (σ∘τ)(i)=σ(τ(i))(\sigma \circ \tau)(i) = \sigma(\tau(i)): apply τ\tau first, then σ\sigma, reading right to left. Often write στ\sigma\tau for σ∘τ\sigma \circ \tau. With zero-based arrays, compose(s, t) = [s[t[i]] for i in range(n)], simply s[t] in NumPy.

Inverse. σ−1\sigma^{-1} reverses arrows: if σ(i)=j\sigma(i) = j, then σ−1(j)=i\sigma^{-1}(j) = i. In two lines swap rows and reorder; in code q[p[i]] = i, or np.argsort(p) in NumPy.

Disjoint cycles

Draw elements in a circle and an arrow from each ii to σ(i)\sigma(i). Since σ\sigma is bijective, each point has exactly one outgoing and one incoming arrow. Such a graph can only be a union of disjoint circuits: following arrows from any point ii eventually returns to it.

InteractivePermutations as arrows and cycles
12345671234567
i1234567σ(i)4176523
  • arrow i→σ(i)i \to \sigma(i), color by cycle
  • fixed point
  • token tt, at position σk(t)\sigma^k(t)
Number of elements nn
Move tokens
Change permutation
σ\sigma in cycles(1 4 6 2)(3 7)(1\,4\,6\,2)(3\,7)
Cycle type(4, 2, 1)
Sign(−1)7−3=(−1)12=+1(-1)^{7 - 3} = (-1)^{12} = +1
Order of σ\sigmalcm⁡(4,2,1)=4\operatorname{lcm}(4, 2, 1) = 4
Tokens home after kk stepsk = 0: 7 of 7
Transpositions applied0
Each element has an arrow to its image; arrows in one cycle share a color. Drag from one element to another to redirect its arrow: to keep σ\sigma bijective, the arrow arriving at the destination points where the moved one pointed. Observe the cycle count when the two elements were in the same versus different cycles, and note the sign. Click ‘Apply σ’ repeatedly: when do all pieces return to their squares?

A cycle has kk writings according to starting point: (1 4 6 2)=(4 6 2 1)=(6 2 1 4)=(2 1 4 6)(1\,4\,6\,2) = (4\,6\,2\,1) = (6\,2\,1\,4) = (2\,1\,4\,6). Disjoint cycles commute because they move different element sets.

Proof

Define i∼ji \sim j on XX if j=σm(i)j = \sigma^m(i) for some integer mm. This is an equivalence relation: reflexive with m=0m = 0, symmetric with −m-m and transitive by adding exponents. Its classes partition XX.

Fix a class and ii within it. Sequence i,σ(i),σ2(i),…i, \sigma(i), \sigma^2(i), \dots takes values in a finite set, so repeats: 0≤a<b0 \le a < b exist with σa(i)=σb(i)\sigma^a(i) = \sigma^b(i) and applying σ−a\sigma^{-a} gives σb−a(i)=i\sigma^{b-a}(i) = i. Let kk be the smallest positive integer with σk(i)=i\sigma^k(i) = i. Elements i,σ(i),…,σk−1(i)i, \sigma(i), \dots, \sigma^{k-1}(i) are distinct (an earlier repeat gives a shorter return) and form the whole class, since any σm(i)\sigma^m(i) equals σm mod k(i)\sigma^{m \bmod k}(i). On that class σ\sigma acts as (i  σ(i)  ⋯  σk−1(i))(i\;\sigma(i)\;\cdots\;\sigma^{k-1}(i)). Since σ\sigma maps each class to itself, it is the product of cycles of classes of size at least 2 (size-1 classes are fixed points).

Uniqueness: in any disjoint-cycle product for σ\sigma, the cycle containing ii must be (i  σ(i)  σ2(i)  ⋯ )(i\;\sigma(i)\;\sigma^2(i)\;\cdots), since other cycles move neither ii nor its images. Thus σ\sigma determines the cycles of σ\sigma.

∎

The cycle decomposition is a permutation’s X-ray. Cycle lengths, including fixed points and sorted decreasingly, form its cycle type: the earlier σ\sigma has type (4,2,1)(4, 2, 1). Many properties depend only on type: sign, order and, as you will see, fixed points of each power.

Proof

Write the n!n! orderings of [n][n], adding parentheses by type: the first m1m_1 elements as 1-cycles, then pairs, and so on. Each ordering gives a permutation of the requested type, and all appear. The same permutation appears exactly ∏kkmkmk!\prod_k k^{m_k} m_k! times: each kk-cycle can begin at any of its kk elements, and its mkm_k equal-length cycles can be written in any of mk!m_k! orders. The quotient rule gives the formula.

∎

For example in S4S_4 there are 11 identity, 242⋅2=6\frac{24}{2\cdot 2} = 6 transpositions, 2422⋅2!=3\frac{24}{2^2\cdot 2!} = 3 type-(2,2)(2,2) permutations, 243=8\frac{24}{3} = 8 3-cycles and 244=6\frac{24}{4} = 6 4-cycles: 1+6+3+8+6=241 + 6 + 3 + 8 + 6 = 24. In each case kk denotes a cycle length.

Transpositions, inversions and sign

Every permutation is a product of transpositions. It suffices to show this for a cycle, checked by following each element under right-to-left composition:

(a1 a2 ⋯ ak)=(a1 ak)(a1 ak−1)⋯(a1 a3)(a1 a2).(a_1\,a_2\,\cdots\,a_k) = (a_1\,a_k)(a_1\,a_{k-1})\cdots(a_1\,a_3)(a_1\,a_2).

There are k−1k - 1 transpositions. Thus a permutation with cc cycles (including fixed points) is a product of ∑(kj−1)=n−c\sum (k_j - 1) = n - c transpositions. Decomposition is not unique: (1 2)=(1 3)(2 3)(1 3)(1\,2) = (1\,3)(2\,3)(1\,3) uses three. Surprisingly, the parity of the number of transpositions is unique. The key is what the figure showed when redirecting an arrow.

Proof

Cycles containing neither aa nor bb are unchanged. If aa and bb share a cycle, write (a x1 ⋯ xr b y1 ⋯ ys)(a\,x_1\,\cdots\,x_r\,b\,y_1\,\cdots\,y_s) with r,s≥0r, s \ge 0. Then σ(a)=x1\sigma(a) = x_1 (or bb if r=0r = 0) and σ(b)=y1\sigma(b) = y_1 (or aa if s=0s = 0). Composition σ′=σ∘(a b)\sigma' = \sigma \circ (a\,b) agrees with σ\sigma except σ′(a)=σ(b)\sigma'(a) = \sigma(b) and σ′(b)=σ(a)\sigma'(b) = \sigma(a). Following arrows, a→y1→⋯→ys→aa \to y_1 \to \cdots \to y_s \to a and b→x1→⋯→xr→bb \to x_1 \to \cdots \to x_r \to b: two cycles (a y1 ⋯ ys)(b x1 ⋯ xr)(a\,y_1\,\cdots\,y_s)(b\,x_1\,\cdots\,x_r). For different cycles (a x1 ⋯ xr)(b y1 ⋯ ys)(a\,x_1\,\cdots\,x_r)(b\,y_1\,\cdots\,y_s), the same image swap gives a→y1→⋯→ys→b→x1→⋯→xr→aa \to y_1 \to \cdots \to y_s \to b \to x_1 \to \cdots \to x_r \to a: one cycle. (The same calculation backward: merge undoes split.)

∎
Proof

Construct σ\sigma from the identity, with nn cycles: id⁡\operatorname{id}, τ1\tau_1, τ1τ2\tau_1\tau_2, …, τ1⋯τm\tau_1\cdots\tau_m. Each step multiplies on the right by a transposition and, by the lemma, changes cycle count by ±1\pm 1, hence changes parity. After mm steps c(σ)≡n−m(mod2)c(\sigma) \equiv n - m \pmod 2.

∎

A kk-cycle of SnS_n has c=1+(n−k)c = 1 + (n - k) cycles (itself plus n−kn - k fixed points), so n−c=k−1n - c = k - 1 and its parity is that of k−1k - 1: transpositions are odd, 3-cycles even, and even-length cycles odd. The common hand-calculation mistake: a kk-cycle has kk symbols but k−1k - 1 transpositions.

Inversions. An inversion of σ\sigma is a pair of positions i<ji < j with σ(i)>σ(j)\sigma(i) > \sigma(j): two elements reordered oppositely. The permutation σ=4 1 7 6 5 2 3\sigma = 4\,1\,7\,6\,5\,2\,3 has 12 (4 precedes 1, 2 and 3; 7 precedes 6, 5, 2 and 3; and so on). Swapping two positions changes inversion-count parity; you will prove it step by step in exercises. Since identity has no inversions and an mm-transposition decomposition is mm position swaps from identity, inv⁡(σ)≡m(mod2)\operatorname{inv}(\sigma) \equiv m \pmod 2 and

sgn⁡(σ)=(−1)inv⁡(σ).\operatorname{sgn}(\sigma) = (-1)^{\operatorname{inv}(\sigma)}.

The figure’s sign display calculates both: for type (4,2,1)(4, 2, 1), (−1)7−3=(−1)12=+1(-1)^{7-3} = (-1)^{12} = +1.

Sign is multiplicative. If σ\sigma uses mm transpositions and τ\tau uses m′m', στ\sigma\tau uses m+m′m + m', so

sgn⁡(στ)=sgn⁡(σ)sgn⁡(τ),sgn⁡(σ−1)=sgn⁡(σ).\operatorname{sgn}(\sigma\tau) = \operatorname{sgn}(\sigma)\operatorname{sgn}(\tau), \qquad \operatorname{sgn}(\sigma^{-1}) = \operatorname{sgn}(\sigma).

This makes Leibniz’s formula work: swapping two columns of A\mat{A} composes each σ\sigma with a transposition and changes every term’s sign, so the determinant changes sign. The linear-algebra determinant lesson develops this.

Algebraic structures: semigroups, monoids and groups

Permutations of [n][n] under composition form a structure ubiquitous in computing. Isolating it abstractly is worthwhile: the same three properties explain parallel reduce, why GPU sums can differ between runs, and logarithmic-time linear recurrences.

SetOperationIdentityGroup?
N\N++00no: 11 has no additive inverse in N\N
Z\Z, Zn\Z_n++ (modulo nn)00yes
strings Σ∗\Sigma^*concatenationempty stringno, and noncommutative
R∪{−∞}\R \cup \{-\infty\}max⁡\max−∞-\inftyno
functions X→XX \to Xcompositionid⁡X\operatorname{id}_Xno, if ∣X∣≥2\abs{X} \ge 2
bijections X→XX \to Xcompositionid⁡X\operatorname{id}_Xyes
n×nn \times n matricesproductIn\mat{I}_nno; invertible ones are
affine maps h↦ah+bh \mapsto ah + bcompositionh↦hh \mapsto hno, if a=0a = 0 is allowed

Subtraction is not associative ((5−3)−1≠5−(3−1)(5 - 3) - 1 \neq 5 - (3 - 1)), nor is averaging two numbers. Floating-point addition is not either, as the cell shows. (N>0,+)(\N_{>0}, +) is a semigroup without identity.

Three elementary facts, with one-line proofs:

  1. Identity is unique: if ee and e′e' are identities, e=e⋅e′=e′e = e \cdot e' = e'.
  2. Inverse is unique: if bb and cc invert aa, b=b(ac)=(ba)c=cb = b(ac) = (ba)c = c. Also (ab)−1=b−1a−1(ab)^{-1} = b^{-1}a^{-1}, reversed, since (ab)(b−1a−1)=a(bb−1)a−1=e(ab)(b^{-1}a^{-1}) = a(bb^{-1})a^{-1} = e.
  3. Invertible elements of a monoid form a group: they include identity; products are invertible by the previous point; inverses of invertible elements are invertible.

Applying 3 to the monoid of all functions [n]→[n][n] \to [n] shows its invertible elements, bijections, form a group: exactly the permutation group.

Why associativity matters. In a semigroup all parenthesizations of a1⋅a2⋯ana_1 \cdot a_2 \cdots a_n give the same result (generalized associativity by induction on nn), so the unparenthesized expression makes sense. Calculate it as a tree: pair neighbors, combine in parallel and repeat, in ⌈log⁡2n⌉\lceil \log_2 n \rceil levels instead of n−1n - 1 sequential steps. This is parallel reduction; computing all prefixes a1⋯ata_1 \cdots a_t extends it to a parallel scan, needing only an associative operator. Identity pads when nn is not a power of 2 and defines empty-list reduction. Commutativity is unnecessary: the tree preserves factor order.

The table’s last row has broad consequences. Recurrence ht=atht−1+bth_t = a_t h_{t-1} + b_t looks inherently sequential, but each step is affine map ft(h)=ath+btf_t(h) = a_t h + b_t and hT=(fT∘⋯∘f1)(h0)h_T = (f_T \circ \cdots \circ f_1)(h_0). Composition is associative and affine composition remains affine, (a2,b2)∘(a1,b1)=(a2a1, a2b1+b2)(a_2, b_2) \circ (a_1, b_1) = (a_2 a_1,\ a_2 b_1 + b_2), so the recurrence reduces in a tree. Selective state-space models use this to train in parallel (linear recurrences with associative scan).

[ ]Associativity: trees, floating point and recurrencesBrowser
import math
import numpy as np
from functools import reduce

print("(0.1 + 0.2) + 0.3 =", (0.1 + 0.2) + 0.3, "   0.1 + (0.2 + 0.3) =", 0.1 + (0.2 + 0.3))

x = np.random.default_rng(0).standard_normal(100_000).astype(np.float32)
exacta = math.fsum(x.astype(np.float64))
secuencial = np.float32(0)
for v in x:                                     # ((x0 + x1) + x2) + ...
    secuencial = secuencial + v

def arbol(v):                                   # (x0 + x1) + (x2 + x3) + ... por niveles
    while len(v) > 1:
        if len(v) % 2:
            v = np.append(v, np.float32(0))     # 0 es el neutro: rellenar no cambia el resultado
        v = v[0::2] + v[1::2]
    return v[0]

print(f"suma exacta {exacta:.6f}   secuencial float32 {secuencial:.6f}   en árbol float32 {arbol(x):.6f}")

# el monoide de las aplicaciones afines h -> a h + b, con la composición
def combina(f, g):
    """g después de f: h -> a2 (a1 h + b1) + b2."""
    (a1, b1), (a2, b2) = f, g
    return (a2 * a1, a2 * b1 + b2)

NEUTRO = (1.0, 0.0)

rng = np.random.default_rng(1)
a, b = rng.uniform(0.5, 1.0, 16), rng.normal(size=16)
h = 0.0
for t in range(16):                             # la recurrencia h_t = a_t h_{t-1} + b_t, en serie
    h = a[t] * h + b[t]

def reduce_arbol(xs):
    while len(xs) > 1:
        xs = [combina(xs[i], xs[i + 1]) if i + 1 < len(xs) else xs[i] for i in range(0, len(xs), 2)]
    return xs[0]

A, B = reduce_arbol(list(zip(a, b)))
print(f"recurrencia en serie: h_16 = {h:.12f}   por árbol (4 niveles): {A * 0.0 + B:.12f}")
print("con el neutro delante y detrás, mismo resultado:", reduce(combina, [NEUTRO] + list(zip(a, b)) + [NEUTRO]) == reduce(combina, list(zip(a, b))))

Sequential float32 sum differs from the exact value by around 10−410^{-4} and tree sum by roughly four times less: two evaluation orders of an operation associative over reals yield different floating-point results. Thus two runs of the same GPU reduction, with threads finishing in different order, may not match bit-for-bit (GPU nondeterminism). Tree sum is also more than parallel: its error bound grows as O(εlog⁡n)\bigO(\eps\log n) instead of O(εn)\bigO(\eps n), why np.sum uses pairwise summation.

The symmetric group

Three recurring subgroups:

  • Alternating group An={σ:sgn⁡σ=+1}A_n = \{\sigma : \operatorname{sgn}\sigma = +1\}, of order n!/2n!/2 for n≥2n \ge 2. It is a subgroup because sign is multiplicative and has half the elements because σ↦σ∘(1 2)\sigma \mapsto \sigma \circ (1\,2) bijects evens and odds.
  • Cyclic subgroup generated by σ\sigma, ⟨σ⟩={id⁡,σ,σ2,… }\langle\sigma\rangle = \{\operatorname{id}, \sigma, \sigma^2, \dots\}.
  • Dihedral group D4D_4 of the square’s 8 symmetries (4 rotations, 4 reflections). Each permutes squares of an n×nn \times n board, and for n≥2n \ge 2 distinct symmetries give distinct permutations, so D4D_4 is a subgroup of Sn2S_{n^2}. In the board interactive, rr rotates 90° and s∣s_{|}, s−s_{-}, s╲s_{\diagdown}, s╱s_{\diagup} reflect about vertical, horizontal and diagonal axes.
Proof

Disjoint cycles commute, so if σ=c1c2⋯cr\sigma = c_1 c_2 \cdots c_r, then σk=c1kc2k⋯crk\sigma^k = c_1^k c_2^k \cdots c_r^k, and since cjkc_j^k move disjoint sets, σk=id⁡\sigma^k = \operatorname{id} exactly when cjk=id⁡c_j^k = \operatorname{id} for every jj. An ℓ\ell-cycle satisfies ck=id⁡c^k = \operatorname{id} exactly when ℓ\ell divides kk, because ckc^k moves each cycle element kk positions. Thus σk=id⁡\sigma^k = \operatorname{id} exactly when kk is a common multiple of all lengths, smallest being their lcm.

∎

In the arrow figure, “Apply σ” moves each piece one cycle step: 4-cycle pieces return every 4 steps and 2-cycle pieces every 2, all first home after mcm⁡(4,2)=4\operatorname{mcm}(4, 2) = 4 steps. Order may exceed nn: in S10S_{10} type (5,3,2)(5, 3, 2) has order 30. Maximum order in SnS_n, Landau’s function g(n)g(n), grows like e(1+o(1))nln⁡ne^{(1 + o(1))\sqrt{n\ln n}}; repeated perfect deck shuffling restores original order after exactly the corresponding permutation’s order.

Group actions, orbits and stabilizers

Groups matter through what they do to other objects. D4D_4 permutes not only squares but colored boards, Go positions and images. SnS_n permutes sequence tokens or graph nodes.

Each gg acts as a permutation of XX (its inverse is the action of g−1g^{-1}), so an action views GG as a permutation group on XX. Examples:

  • SnS_n acts on [n][n] by σ⋅i=σ(i)\sigma \cdot i = \sigma(i). The orbits of ⟨σ⟩\langle\sigma\rangle are exactly the cycles of σ\sigma: the cycle-decomposition proof was an orbit argument.
  • D4D_4 acts on board squares and hence colorings f:squares→{1,…,k}f: \text{squares} \to \{1, \dots, k\} by (g⋅f)(x)=f(g−1x)(g \cdot f)(x) = f(g^{-1}x): square g(x)g(x) receives the color of xx. The g−1g^{-1} ensures g⋅(h⋅f)=(gh)⋅fg \cdot (h \cdot f) = (gh) \cdot f.
  • SnS_n acts on adjacency matrices of nn-node graphs by renaming nodes. Graphs are in the same orbit exactly when isomorphic.

Orbits are equivalence classes of x∼y  ⟺  y=g⋅xx \sim y \iff y = g \cdot x for some gg (reflexive via ee, symmetric via g−1g^{-1}, transitive via product), so partition XX. Counting “objects up to symmetry” counts orbits. The stabilizer is a subgroup of GG: it contains ee and if gg and hh fix xx, so do ghgh and g−1g^{-1}.

Proof

Let H=Estab⁡(x)H = \operatorname{Estab}(x). Two elements send xx to the same place exactly when they differ by an element of HH: g⋅x=g′⋅x  ⟺  g−1g′⋅x=x  ⟺  g′∈gHg \cdot x = g' \cdot x \iff g^{-1}g' \cdot x = x \iff g' \in gH, where gH={gh:h∈H}gH = \{gh : h \in H\}. Thus the map g↦g⋅xg \mapsto g \cdot x from GG onto Orb⁡(x)\operatorname{Orb}(x) has fibers gHgH, each with ∣H∣\abs{H} elements (h↦ghh \mapsto gh is injective). GG partitions into ∣Orb⁡(x)∣\abs{\operatorname{Orb}(x)} fibers of size ∣H∣\abs{H}.

∎

A board without symmetry has stabilizer {e}\{e\} and orbit size 8; one with only diagonal reflection has stabilizer {e,s╲}\{e, s_{\diagdown}\} and orbit size 4; one symmetric under all has orbit size 1. Orbit sizes always divide ∣G∣\abs{G}.

Proof

HH acts on GG by h⋅g=hgh \cdot g = hg. No h≠eh \neq e fixes anything (hg=g⇒h=ehg = g \Rightarrow h = e), so every orbit has ∣H∣\abs{H} elements and orbits partition GG. For the second part use H=⟨g⟩H = \langle g \rangle, with as many elements as the order of gg.

∎

Burnside’s lemma

How many black-and-white 3×33 \times 3 boards are there up to rotations and reflections? There are 29=5122^9 = 512 colorings and 8 symmetries, but the answer is not 512/8=64512/8 = 64: division by ∣G∣\abs{G} works only if every orbit has size ∣G∣\abs{G}, i.e. no board has any symmetry, while the all-white board has all of them. Burnside counts the other way: rather than each board’s symmetries, count boards fixed by each symmetry.

This is the common form of Burnside’s lemma (also known to Cauchy and Frobenius). The proof double-counts {(g,x):g⋅x=x}\{(g, x) : g \cdot x = x\} first by rows then columns:

∑g∈G∣Fix⁡(g)∣=∣{(g,x):g⋅x=x}∣\sum_{g \in G} \abs{\operatorname{Fix}(g)} = \abs{\{(g, x) : g \cdot x = x\}}
Count pairs grouped by gg: each gg corresponds to ∣Fix⁡(g)∣\abs{\operatorname{Fix}(g)} pairs.
1/5

The final steps are the essence: each point in an orbit of size ∣O∣\abs{O} weighs 1/∣O∣1/\abs{O}, so each orbit contributes exactly 1, large or small.

Fixed colorings. For kk colors, ∣Fix⁡(g)∣\abs{\operatorname{Fix}(g)} is easy: coloring ff is fixed by gg exactly when f(g(x))=f(x)f(g(x)) = f(x) for every square xx, i.e. it is constant on each cycle of gg as a square permutation. Choose one color per cycle:

∣Fix⁡(g)∣=k c(g),c(g)=number of cycles of g (including fixed points).\abs{\operatorname{Fix}(g)} = k^{\,c(g)}, \qquad c(g) = \text{number of cycles of } g \text{ (including fixed points)}.

Counting up to symmetry reduces to each group element’s cycle structure, learned in the first half.

InteractiveBoards up to symmetry
Arrows: rr (90° clockwise rotation) moves each cell. There are 3 cycles, so it fixes 23=82^{3} = 8 colorings.
The orbit: the board transformed by each element of GG
Colored border: the element leaves the board unchanged (it is in the stabilizer). Dimmed: repeated images.
ggsymmetrycell cyclesfixed coloringsfixes yours?
eeidentity929=5122^{9} = 512yes
rr90° clockwise rotation323=82^{3} = 8no
r2r^2180° rotation525=322^{5} = 32no
r3r^3270° clockwise rotation323=82^{3} = 8no
s∣s_{|}vertical reflection626=642^{6} = 64no
s−s_{-}horizontal reflection626=642^{6} = 64no
s╲s_{\diagdown}diagonal reflection626=642^{6} = 64yes
s╱s_{\diagup}antidiagonal reflection626=642^{6} = 64no
Average over GG (number of orbits)8168=102\tfrac{816}{8} = 1022
Dividing by ∣G∣|G| gives 64, fewer than the 102 actual orbits: symmetric boards have orbits smaller than 8, so division undercounts them.
Board n×nn \times n
Colors kk
Group
Orbit size (distinct thumbnails)4
Stabilizer size (thumbnails matching the original)2
∣Orb⁡∣⋅∣Estab⁡∣=∣G∣|\operatorname{Orb}| \cdot |\operatorname{Estab}| = |G|4 · 2 = 8
Distinct boards (Burnside)816 / 8 = 102
Naive count kn2/∣G∣k^{n^2}/|G|512 / 8 = 64
Color the board by clicking squares. At right, the orbit: the board transformed by each of the 8 elements of D4D_4; colored-bordered thumbnails match the original (forming the stabilizer), dimmed ones repeat earlier thumbnails. Check that distinct-thumbnail count times original-matching count always gives ∣G∣\abs{G}, which is 8 for D4D_4. Click a table row: arrows show that symmetry as a square permutation, and a fixed coloring must be constant on each cycle. Compare the fixed-coloring column's average with naive division, then switch to C4C_4 (rotations only).

For a 3×33 \times 3 board: identity has 9 cycles; 90° and 270° rotations have 3 (center and two 4-cycles, corners and edges); 180° has 5 (center and four opposite pairs); each reflection has 6 (three on its axis and three pairs). With k=2k = 2,

29+2⋅23+25+4⋅268=512+16+32+2568=8168=102.\frac{2^9 + 2\cdot 2^3 + 2^5 + 4\cdot 2^6}{8} = \frac{512 + 16 + 32 + 256}{8} = \frac{816}{8} = 102.

There are 102 distinct boards, not 64. Naive division always undercounts because each small orbit contributes less than 1 to ∣X∣/∣G∣\abs{X}/\abs{G}. Relative discrepancy vanishes on large boards: the vast majority of 19×1919 \times 19 colorings have no symmetry and orbits of size 8.

Necklaces. An nn-bead necklace with kk colors, up to rotation, is an orbit of cyclic group CnC_n acting on length-nn strings. Rotation by jj positions has gcd⁡(j,n)\gcd(j, n) cycles (each traverses positions in a class modulo gcd⁡(j,n)\gcd(j, n)), so

necklaces(n,k)=1n∑j=0n−1kgcd⁡(j,n).\text{necklaces}(n, k) = \frac{1}{n}\sum_{j=0}^{n-1} k^{\gcd(j, n)}.

With n=4n = 4 and k=2k = 2: (24+21+22+21)/4=24/4=6(2^4 + 2^1 + 2^2 + 2^1)/4 = 24/4 = 6, namely 0000, 0001, 0011, 0101, 0111 and 1111. If n=pn = p is prime, every nontrivial rotation has one cycle and the formula gives (kp+(p−1)k)/p(k^p + (p - 1)k)/p. Integrality says kp≡kk^p \equiv k in arithmetic modulo pp: Fermat’s little theorem, proved in exercises.

[ ]Burnside versus brute forceBrowser
import itertools

def cycles(p):
    seen, out = [False] * len(p), []
    for i in range(len(p)):
        if not seen[i]:
            c, j = [], i
            while not seen[j]:
                seen[j] = True
                c.append(j)
                j = p[j]
            out.append(c)
    return out

def d4_cell_perms(n):
    """Las 8 simetrías del cuadrado como permutaciones de las n² casillas (índice r·n + c)."""
    maps = {
        "e":   lambda r, c: (r, c),
        "r":   lambda r, c: (c, n - 1 - r),          # giro de 90° (horario)
        "r²":  lambda r, c: (n - 1 - r, n - 1 - c),
        "r³":  lambda r, c: (n - 1 - c, r),
        "s|":  lambda r, c: (r, n - 1 - c),          # reflexión respecto al eje vertical
        "s-":  lambda r, c: (n - 1 - r, c),          # respecto al eje horizontal
        "s\\": lambda r, c: (c, r),                  # diagonal principal
        "s/":  lambda r, c: (n - 1 - c, n - 1 - r),  # antidiagonal
    }
    return {name: [f(r, c)[0] * n + f(r, c)[1] for r in range(n) for c in range(n)] for name, f in maps.items()}

def image(col, g):
    """La casilla g(x) recibe el color de x."""
    out = [0] * len(col)
    for x, gx in enumerate(g):
        out[gx] = col[x]
    return tuple(out)

def orbits_burnside(n, k):
    G = d4_cell_perms(n)
    return sum(k ** len(cycles(g)) for g in G.values()) // len(G)

def orbits_brute(n, k):
    """Cuenta un representante por órbita: el mínimo lexicográfico."""
    G = list(d4_cell_perms(n).values())
    return sum(1 for col in itertools.product(range(k), repeat=n * n)
               if col == min(image(col, g) for g in G))

for n in (2, 3):
    G = d4_cell_perms(n)
    print(f"n = {n}: ciclos de cada simetría", {g: len(cycles(p)) for g, p in G.items()})
    for k in (2, 3):
        b, f = orbits_burnside(n, k), orbits_brute(n, k)
        print(f"   k = {k}: Burnside {b:5d}   fuerza bruta {f:5d}   ingenuo k^(n²)/8 = {k**(n*n)/8:.3f}")

for n in (4, 9, 19):
    b = orbits_burnside(n, 3)
    print(f"{n}×{n} con 3 estados por casilla: {b:.4e} órbitas;  órbitas / (3^{n*n} / 8) = {b / (3**(n*n) / 8):.12f}")

The last line’s ratio measures naive division error: at 4×44 \times 4 already only 0.3%, and at 9×99 \times 9 and 19×1919 \times 19 the ratio equals 1 to all twelve displayed digits. (All colorings with empty, black and white are counted, legal or not.)

Game symmetries and data augmentation

Burnside applies to any group-invariant set, not only all colorings. Legal tic-tac-toe positions (reachable from an empty board without continuing after victory) form such a set, because rotating or reflecting a legal game gives another legal game.

[ ]Tic-tac-toe up to symmetryBrowser
from collections import Counter

LINEAS = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]

def gana(b, j):
    return any(b[x] == b[y] == b[z] == j for x, y, z in LINEAS)

def posiciones_legales():
    """Posiciones alcanzables desde el tablero vacío (X = 1 empieza, O = 2)."""
    vistas, pila = {(0,) * 9}, [(0,) * 9]
    while pila:
        b = pila.pop()
        if gana(b, 1) or gana(b, 2) or 0 not in b:
            continue                                   # partida terminada
        j = 1 if b.count(1) == b.count(2) else 2
        for i in range(9):
            if b[i] == 0:
                nb = b[:i] + (j,) + b[i + 1:]
                if nb not in vistas:
                    vistas.add(nb)
                    pila.append(nb)
    return vistas

P = posiciones_legales()
G = list(d4_cell_perms(3).values())
clases = {min(image(b, g) for g in G) for b in P}
fijas = [sum(1 for b in P if image(b, g) == b) for g in G]
print("posiciones legales:", len(P), "   salvo simetría:", len(clases))
print("puntos fijos de cada simetría:", fijas, "   Burnside:", sum(fijas), "/ 8 =", sum(fijas) / 8)
print("tamaño de la órbita de cada posición:", dict(Counter(len({image(b, g) for g in G}) for b in P)))

There are 5478 legal positions and only 765 essentially distinct: a learning program may treat each class once. Fixed points across symmetries sum to 6120 and 6120/8=7656120/8 = 765, as predicted. Orbits smaller than 8 are not rare on such small boards: 564 positions have orbit size 4.

This is AlphaGo Zero’s use of symmetry. Go rules are unchanged by rotation or reflection, so if (s,π,z)(s, \pi, z) is a training example (position, search policy, result), so is (g⋅s,g⋅π,z)(g \cdot s, g \cdot \pi, z) for every g∈D4g \in D_4: policy transforms with position and value does not change. Silver et al. (2017) augmented each position with all 8 images and evaluated the network during search on a randomly chosen symmetry. AlphaZero abandoned both to handle chess and shogi with the same algorithm, whose boards lack those symmetries (Silver et al., 2018). See game symmetry augmentation. Augmenting with the orbit teaches invariance; alternatively build it into architecture, compared in augmentation versus equivariance.

Parity invariants: the 15-puzzle

The 15-puzzle is a 4×44 \times 4 frame with 15 numbered tiles and a gap; a move slides an adjacent tile into the gap. It became a craze in 1880, and years later Sam Loyd claimed its invention (actually Noyes Chapman’s idea) and an offer of a $1,000 prize for solving the configuration with 14 and 15 swapped. Nobody collected it: that configuration is impossible, as Johnson and Story proved in 1879 in the American Journal of Mathematics. Play before reading the proof.

InteractiveThe impossible 15-puzzle
Parity history (recent moves, newest on the right)
move·inversionsblank rowsum
  • even
  • odd
  • ↔ horizontal, ↕ vertical, ✕ cheat, · start or shuffle
Configuration
Cheat
Legal moves0
Inversions (15 tiles)1, odd
Blank row (from bottom)1, odd
Sum (invariant)2 ≡ 0 mod 2
Another form: sgn⁡(π16)⋅(−1)d\operatorname{sgn}(\pi_{16})\cdot(-1)^{d}−1⋅(−1)0=−1-1 \cdot (-1)^{0} = -1
Inversions + blank row is even. In the solution it is odd (0 + 1), and no move changes its parity: the solution is unreachable from here.
Move tiles by clicking (or arrow keys after selecting the board). The panel counts inversions of the 15 tiles in row order and the gap's row counted from below. Make horizontal and vertical moves and watch the log: which rows change color for each move type and which never changes? Then cheat by swapping two tiles manually and see the invariant.
Proof

A move swaps the gap’s contents with a neighboring square, composing π\pi with a transposition and changing its sign. Simultaneously the gap moves one square horizontally or vertically, so dd changes by ±1\pm 1 and (−1)d(-1)^d changes sign too. The product remains equal. At the solution π=id⁡\pi = \operatorname{id} and d=0d = 0: product +1+1. In Loyd’s configuration π=(14  15)\pi = (14\;15) and d=0d = 0: product −1-1.

∎

The panel uses an equivalent board-friendly form: the inversion count NN of the 15 tiles in reading order (ignoring the gap) plus the gap row rr counted from below. A horizontal move changes neither reading order nor row. A vertical move sends one tile 4 reading-order positions forward or back across 3 intermediate tiles: each of those three pairs changes inversion status, so NN changes by ±1\pm 1 or ±3\pm 3, odd, while rr changes by 1. Parity of N+rN + r is preserved. At the solution it is 0+10 + 1, odd; in Loyd’s configuration 1+11 + 1, even.

That configurations with correct invariant are all reachable (exactly half of 16!16!) is harder, also proved by Johnson and Story; A. F. Archer gives a short modern proof (American Mathematical Monthly, 1999). The pattern is general: an invariant is a quantity no allowed step changes, like a loop invariant proving a program never reaches a bad state, and permutation parity is especially powerful. It explains why only two Rubik’s cube edges cannot be swapped, or why half of tile-game positions are unreachable.

Fisher–Yates shuffle

We want to generate a permutation of nn elements uniformly at random: each of n!n! with probability 1/n!1/n!, in a probability space whose only randomness is a uniform-integer generator.

Proof

Counting paths. An execution is determined by choices (jn−1,…,j1)(j_{n-1}, \dots, j_1) with ji∈{0,…,i}j_i \in \{0, \dots, i\}. There are n⋅(n−1)⋯2=n!n \cdot (n-1) \cdots 2 = n! sequences, each with probability 1/n!1/n!. Show distinct sequences give distinct orderings; then paths and orderings are in bijection between two n!n!-element sets. After step ii, position ii is untouched, so the final result has in position n−1n-1 the element chosen first, in n−2n-2 the second, and so on. If two sequences first differ at step ii, arrays are identical until then and put different elements at ii, never moving again: final orderings differ.

Loop invariant. At iteration ii‘s start: for each sequence (yi+1,…,yn−1)(y_{i+1}, \dots, y_{n-1}) of distinct elements, the probability that a[i+1..n-1] equals it is (i+1)!n!\frac{(i+1)!}{n!} (the suffix is uniform among n!/(i+1)!n!/(i+1)! possibilities), and a[0..i] contains the remaining i+1i + 1 elements. Initially (i=n−1i = n - 1) the suffix is empty, probability n!/n!=1n!/n! = 1. At step ii, conditioned on the suffix, a[j] with uniform jj in {0,…,i}\{0, \dots, i\} is uniform among the i+1i + 1 remaining elements, so each extended suffix has probability (i+1)!n!⋅1i+1=i!n!\frac{(i+1)!}{n!}\cdot\frac{1}{i+1} = \frac{i!}{n!}: the invariant for i−1i - 1. At loop end (i=0i = 0), a[1..n-1] is uniform with probability 1n!\frac{1}{n!} for each sequence, and a[0] is determined.

∎

Naive shuffle. An apparently reasonable variant traverses i=0,…,n−1i = 0, \dots, n-1 and swaps a[i] with a[j] for uniform jj in the whole list {0,…,n−1}\{0, \dots, n-1\}. There are nnn^n equiprobable choice sequences, each producing an ordering. Uniform output would require exactly nn/n!n^n/n! sequences per ordering, an integer. But for n≥3n \ge 3, n!n! does not divide nnn^n: n−1n - 1 divides n!n! and is coprime to nn, so cannot divide nnn^n. For n=3n = 3 there are 2727 paths for 66 orderings, 27/6=4.527/6 = 4.5. Exact counts are 4,5,5,5,4,44, 5, 5, 5, 4, 4: three orderings have probability 5/27≈0.1855/27 \approx 0.185, three 4/27≈0.1484/27 \approx 0.148, versus uniform 1/6≈0.1671/6 \approx 0.167.

InteractiveCorrect versus naive shuffle
00.511.5frequency × n!1234/271325/272135/272315/273124/273214/27
  • Fisher-Yates
  • naive
  • alternative exact probability
  • uniform, 1/n!1/n!
List length
Compare Fisher-Yates with
Shuffles per algorithm30 000
χ2\chi^2 for Fisher-Yates (99.9% threshold: 20.52)2.7
χ2\chi^2 for naive287.1
Exact probability, Fisher-Yates1/6 for all
Exact probability, naivefrom 4/27 to 5/27
There are 33=273^3 = 27 equally likely paths and 3!=63! = 6 permutations. To be uniform, each permutation would need 27/6=4.527/6 = 4.5 paths: this is not an integer, so the naive algorithm cannot be uniform. Exact probabilities range from 4/274/27 to 5/275/27.
Each pair of bars is a permutation of [1, …, n], in one-line notation. Height is observed frequency times n!n!, so uniform is the dashed line at 1; horizontal marks are exact alternative-algorithm probabilities from enumerating all paths. Click ‘Shuffle’ and watch blue bars approach 1 while red bars approach their marks, not the line. Try n=4n = 4 and find the most favored permutation. Then compare the off-by-one error j∈[0,i)j \in [0, i): what do the only possible permutations share?

The readout’s χ2\chi^2 statistic compares frequencies with uniform: with n!−1n! - 1 degrees of freedom, a value above the 99.9th percentile (20.5 for n=3n = 3, 49.7 for n=4n = 4) rejects uniformity with high confidence. Fisher–Yates stays around the degrees of freedom as expected; naive grows linearly with shuffle count because the bias is real and every sample confirms it.

Off by one. Choosing jj in {0,…,i−1}\{0, \dots, i-1\} instead of {0,…,i}\{0, \dots, i\} always swaps the element at ii with another and never leaves it there. Uniform output is impossible: only (n−1)!(n-1)! paths exist. The merge-or-split lemma says exactly what results. Swapping positions ii and jj composes on the right with transposition (i j)(i\,j), and before step ii each cycle contains exactly one of 0,…,i0, \dots, i: initially all fixed points, and step ii merges the cycle of ii with that of j<ij < i, a different one, transferring the property to 0,…,i−10, \dots, i - 1. Each of n−1n - 1 steps merges two cycles, leaving one: output is always an nn-cycle. As in Fisher–Yates, distinct paths produce distinct results, and there are (n−1)!(n-1)! length-nn cycles: all appear exactly once. This is Sattolo’s algorithm (1986), useful for a uniform nn-cycle, e.g. visiting an array randomly in full before repetition. Mistaken for Fisher–Yates it produces shuffles with no fixed point.

Implementation from scratch

Everything above fits a few array functions under this course’s convention: p[i] is σ(i)\sigma(i), zero-based indexing and right-to-left composition. The cell exhaustively checks the proved identities in S6S_6.

[ ]Permutations as arrays: cycles, sign, order and typesBrowser
import itertools, math, random
from collections import Counter

def compose(s, t):
    """(s∘t)(i) = s[t[i]]: primero t, después s."""
    return [s[ti] for ti in t]

def inverse(p):
    q = [0] * len(p)
    for i, pi in enumerate(p):
        q[pi] = i
    return q

def cycles(p):
    """Ciclos disjuntos de p (incluidos los puntos fijos), cada uno desde su menor elemento."""
    seen, out = [False] * len(p), []
    for i in range(len(p)):
        if not seen[i]:
            c, j = [], i
            while not seen[j]:
                seen[j] = True
                c.append(j)
                j = p[j]
            out.append(c)
    return out

def sign_cycles(p):
    return (-1) ** (len(p) - len(cycles(p)))

def inversions(p):
    return sum(1 for i in range(len(p)) for j in range(i + 1, len(p)) if p[i] > p[j])

def sign_inversions(p):
    return (-1) ** inversions(p)

def order(p):
    return math.lcm(*(len(c) for c in cycles(p)))

def show(p):
    cs = [c for c in cycles(p) if len(c) > 1]
    return "".join("(" + " ".join(str(i + 1) for i in c) + ")" for c in cs) or "id"

sigma = [3, 0, 6, 5, 4, 1, 2]           # σ(1) = 4, σ(2) = 1, ... (desde 0 en el código)
print("σ =", show(sigma), "  σ⁻¹ =", show(inverse(sigma)))
print("signo por ciclos:", sign_cycles(sigma), "  por inversiones:", sign_inversions(sigma), f"({inversions(sigma)} inversiones)")
print("orden:", order(sigma))

# comprobaciones exhaustivas en S_6 (720 permutaciones)
S6 = [list(p) for p in itertools.permutations(range(6))]
e = list(range(6))
assert all(sign_cycles(p) == sign_inversions(p) for p in S6)
assert all(compose(p, inverse(p)) == e for p in S6)
rnd = random.Random(0)
pares = [(rnd.choice(S6), rnd.choice(S6)) for _ in range(2000)]
assert all(sign_cycles(compose(p, q)) == sign_cycles(p) * sign_cycles(q) for p, q in pares)
print("S_6: signo por ciclos = por inversiones, y multiplicativo ✓")

# número de permutaciones de cada tipo de ciclos frente a la fórmula n! / ∏ k^m_k m_k!
tipos = Counter(tuple(sorted((len(c) for c in cycles(p)), reverse=True)) for p in S6)
def formula(tipo, n=6):
    m = Counter(tipo)
    return math.factorial(n) // math.prod(k**mk * math.factorial(mk) for k, mk in m.items())
assert all(c == formula(t) for t, c in tipos.items())
for tipo, cuenta in sorted(tipos.items(), key=lambda kv: -kv[1])[:5]:
    print(f"tipo {tipo}: {cuenta:3d} permutaciones = fórmula {formula(tipo)};  orden {math.lcm(*tipo)}")
print("tipos distintos en S_6:", len(tipos), "   orden máximo en S_6:", max(order(p) for p in S6))

Maximum order in S6S_6 is 6, achieved by a 6-cycle and type (3,2,1)(3, 2, 1): Landau’s function at n=6n = 6.

Now Fisher–Yates, naive and Sattolo. distribucion_exacta does not simulate: it traverses all equiprobable choice sequences and counts each resulting ordering. The path-count proof becomes a program. Then a vectorized NumPy simulation and scipy.stats.chisquare χ2\chi^2 test.

[ ]Fisher–Yates: exact distribution and χ² testBrowser
import itertools, math
from collections import Counter
import numpy as np
from scipy.stats import chisquare

def fisher_yates(a, randint):
    """Baraja una copia de a. randint(lo, hi) devuelve un entero uniforme en [lo, hi], extremos incluidos."""
    a = list(a)
    for i in range(len(a) - 1, 0, -1):
        # invariante: a[i+1:] es una ordenación uniforme de len(a)-1-i elementos distintos
        # y a[:i+1] contiene exactamente los restantes
        j = randint(0, i)                    # ¡i incluido!
        a[i], a[j] = a[j], a[i]
    return a

def ingenuo(a, randint):
    a = list(a)
    for i in range(len(a)):
        j = randint(0, len(a) - 1)           # cualquier posición de toda la lista
        a[i], a[j] = a[j], a[i]
    return a

def sattolo(a, randint):
    a = list(a)
    for i in range(len(a) - 1, 0, -1):
        j = randint(0, i - 1)                # error de uno: i excluido
        a[i], a[j] = a[j], a[i]
    return a

def distribucion_exacta(algoritmo, n):
    """Recorre TODAS las sucesiones de elecciones, que son equiprobables."""
    rangos = []
    def randint_grabador(lo, hi):            # una pasada para averiguar el rango de cada paso
        rangos.append(hi - lo + 1)
        return lo
    algoritmo(range(n), randint_grabador)
    cuenta = Counter()
    for camino in itertools.product(*[range(m) for m in rangos]):
        it = iter(camino)
        cuenta[tuple(algoritmo(range(n), lambda lo, hi: lo + next(it)))] += 1
    return cuenta, math.prod(rangos)

for nombre, alg in [("Fisher-Yates", fisher_yates), ("ingenuo", ingenuo), ("Sattolo", sattolo)]:
    for n in (3, 4):
        cuenta, caminos = distribucion_exacta(alg, n)
        print(f"{nombre:12s} n = {n}: {caminos:3d} caminos, {len(cuenta):2d} ordenaciones distintas, "
              f"caminos por ordenación entre {min(cuenta.values())} y {max(cuenta.values())}")

cuenta, _ = distribucion_exacta(sattolo, 4)
print("Sattolo, n = 4: ¿todas son 4-ciclos?", all(len(cycles(list(p))) == 1 for p in cuenta))

rng = np.random.default_rng(0)

def simular(n, N, tipo):
    """N barajados a la vez: cada fila de a es una lista."""
    a = np.tile(np.arange(n), (N, 1))
    filas = np.arange(N)
    pasos = range(n) if tipo == "ingenuo" else range(n - 1, 0, -1)
    for i in pasos:
        alto = n if tipo == "ingenuo" else i + 1
        j = rng.integers(0, alto, size=N)
        ai = a[filas, i].copy()
        a[filas, i] = a[filas, j]
        a[filas, j] = ai
    codigo = a @ (n ** np.arange(n))         # un entero distinto por ordenación
    _, cuentas = np.unique(codigo, return_counts=True)
    return cuentas

N = 240_000
for n in (3, 4):
    for tipo in ("fy", "ingenuo"):
        c = simular(n, N, tipo)
        r = chisquare(c)                     # H0: las n! ordenaciones son equiprobables
        print(f"n = {n}, {tipo:8s}: frecuencia × n! entre {c.min() * math.factorial(n) / N:.3f} y "
              f"{c.max() * math.factorial(n) / N:.3f};  chi2 = {r.statistic:8.1f},  p = {r.pvalue:.3g}")

Exact counts confirm theory: Fisher–Yates yields each ordering along exactly one path; naive divides 27 paths among 6 orderings (4 to 5) and 256 among 24 (8 to 15, nearly double); Sattolo produces only the 6 four-cycles. In simulation, naive with n=4n = 4 produces its favorite ordering 40% more often than warranted, detected with pp indistinguishable from 0, while Fisher–Yates passes.

Note simular: the swap first copies column i. Advanced indexing like a[filas, i] already returns a NumPy copy, but with views the “obvious” swap silently fails: a[0], a[1] = a[1], a[0] on a 2D array’s rows leaves them equal, because right-hand values are views and the second assignment reads the row the first has just overwritten. Every in-place implementation needs similar care.

The professional version

TaskToolNote
Shuffle or permute indicesrng.permutation(n), rng.shuffle(x) with rng = np.random.default_rng(semilla)Fisher–Yates in C
Shuffle in PyTorchtorch.randperm(n, generator=g)used by DataLoader(shuffle=True)
Shuffle a Python listrandom.shuffle(x)Fisher–Yates; beware the 2080-period limit
Cycles, sign, order, inversionssympy.combinatorics.Permutationcomposes left to right
Permutation groups, orbitssympy.combinatorics.PermutationGroupSchreier–Sims algorithm
Enumerate necklaces and braceletssympy.utilities.iterables.necklaces, bracelets
[ ]sympy.combinatorics and numpy.randomBrowser
import numpy as np
from sympy.combinatorics import Permutation, PermutationGroup
from sympy.utilities.iterables import necklaces, bracelets

sigma = [3, 0, 6, 5, 4, 1, 2]
p = Permutation(sigma)
print("ciclos:", p.cyclic_form, "  tipo:", p.cycle_structure, "  signo:", p.signature(),
      "  orden:", p.order(), "  inversiones:", p.inversions())

# la convención de sympy: p*q aplica PRIMERO p y después q
q = Permutation([1, 0, 2, 3, 4, 5, 6])          # la transposición que intercambia 0 y 1
print("sympy p*q:         ", (p * q).array_form)
print("compose(q, p) = q∘p:", compose(q.array_form, sigma))
print("compose(p, q) = p∘q:", compose(sigma, q.array_form))

# D4 actuando sobre las casillas de un 3×3, generado por un giro y una reflexión
n = 3
r = Permutation(d4_cell_perms(n)["r"])
s = Permutation(d4_cell_perms(n)["s|"])
D4 = PermutationGroup([r, s])
print("|D4| =", D4.order(), "  órbitas de las casillas:", [sorted(o) for o in D4.orbits()])
print("collares de 8 cuentas y 2 colores:", len(list(necklaces(8, 2))),
      "  pulseras (también con reflexiones):", len(list(bracelets(8, 2))))

rng = np.random.default_rng(0)
print("rng.permutation(10):", rng.permutation(10))
print("argsort de claves uniformes:", np.argsort(rng.random(10)))

Output confirms the initial warning: sympy p*q equals our compose(q, p), not compose(p, q). The D4D_4 orbits on 3×33 \times 3 squares are three: corners, edges and center. The final trick, sorting by independent random keys, also produces a uniform permutation (continuous keys have tie probability 0 and all relative key orders are equiprobable), but costs O(nlog⁡n)\bigO(n \log n) instead of O(n)\bigO(n). Sorting with a random comparator, sorted(x, key=cmp_to_key(lambda a, b: random.choice([-1, 1]))), is not uniform: result depends on the sorting algorithm and is biased by the same divisibility argument.

In PyTorch, torch.randperm shuffles each DataLoader epoch; fix its generator for reproducible shuffles:

import torch

g = torch.Generator().manual_seed(0)
idx = torch.randperm(10, generator=g)          # una permutación uniforme de 0..9
loader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True, generator=g)

Common mistakes

Exercises

QuizWhich comes first?
With this lesson's convention, (στ)(i)=σ(τ(i))(\sigma\tau)(i) = \sigma(\tau(i)). If σ=(1 2 3)\sigma = (1\,2\,3) and τ=(1 3)\tau = (1\,3) in S3S_3, what is στ\sigma\tau?
NumericOrder of a cycle type
What is the order of a permutation of S10S_{10} with cycle type (2,3,5)(2, 3, 5)?
NumericCounting by cycle type
How many permutations in S6S_6 are products of two disjoint 3-cycles, type (3,3)(3, 3)?
ProofA transposition changes inversion parity
Prove: Let w=w1w2⋯wnw = w_1 w_2 \cdots w_n be a one-line permutation and i<ji < j two positions. Swapping wiw_i and wjw_j changes inversion-count parity. Consequently sgn⁡(σ)=(−1)inv⁡(σ)\operatorname{sgn}(\sigma) = (-1)^{\operatorname{inv}(\sigma)} is well-defined.
0
Let w′w' be the swapped result. An inversion is a pair p<qp < q with wp>wqw_p > w_q. Classify position pairs by how many of ii and jj they contain.

Step 1 of 5. What happens to pairs (p,q)(p, q) containing neither ii nor jj?

NumericSix-bead necklaces
How many distinct 6-bead necklaces with 2 colors exist if rotations count as the same (without reflections)?
Numeric2×2 boards with three colors
How many colorings of a 2×22 \times 2 board with 3 colors are there up to the 8 symmetries of D4D_4?
ProofFermat's little theorem by counting necklaces
Prove: If pp is prime and a≥1a \ge 1 is an integer, then ap≡a(modp)a^p \equiv a \pmod p.
0
Let XX be the set of apa^p length-pp strings over an aa-letter alphabet, and let cyclic group Cp=⟨ρ⟩C_p = \langle\rho\rangle act by rotating one position: ρ⋅(x1x2⋯xp)=xpx1⋯xp−1\rho \cdot (x_1 x_2 \cdots x_p) = x_p x_1 \cdots x_{p-1}.

Step 1 of 4. Which strings does rotation ρj\rho^j with 0<j<p0 < j < p fix?

QuizWhich are solvable?
Which 15-puzzle configurations can reach the solution (1 through 15 in reading order, gap bottom right) by legal moves?

More than one answer may be correct.

QuizIs naive shuffling uniform?
The naive shuffle traverses i=0,…,n−1i = 0, \dots, n - 1 and swaps position ii with uniform position jj in [0,n)[0, n). Is it uniform for n≥3n \ge 3, and why?
CodeBoards up to symmetry with Burnside
Implement count_board_orbits(n, k): the number of colorings of an n×nn \times n board with kk colors up to the 8 symmetries of D4D_4 (rotations and reflections), using Burnside's lemma. Return an exact int and work for large boards (tests include n=19n = 19), so do not enumerate colorings: count each symmetry's cycles as a square permutation, or derive a closed formula by parity of nn.
def count_board_orbits(n, k):
  """Número de coloraciones de un tablero n x n con k colores salvo las 8 simetrías del cuadrado."""
  # tu código: para cada simetría g, cuenta los ciclos c(g) de g sobre las n*n casillas;
  # el resultado es la media de k**c(g)
  return k ** (n * n) // 8
Shift+Enter to run

Summary

Key idea
A permutation is a bijection, and disjoint cycles say almost everything: sign is (−1)n−c(-1)^{n - c} and order is the lcm of lengths. Counting objects up to symmetry counts orbits, and Burnside reduces that to counting cycles: the average of kc(g)k^{c(g)} over the group.
  • Permutations compose as functions, right to left here; sympy uses the reverse. In an array, p[i] = σ(i), composition is s[t] and inverse argsort.
  • Every permutation uniquely decomposes into disjoint cycles, equivalence classes of “j=σm(i)j = \sigma^m(i)”. There are n!/∏kkmkmk!n!/\prod_k k^{m_k} m_k! permutations of each type.
  • Composing with a transposition merges two cycles or splits one, so transposition-count parity is well-defined: sgn⁡σ=(−1)n−c(σ)=(−1)inv⁡(σ)\operatorname{sgn}\sigma = (-1)^{n - c(\sigma)} = (-1)^{\operatorname{inv}(\sigma)}, multiplicative. A kk-cycle has parity k−1k - 1.
  • Semigroup (associative), monoid (plus identity), group (plus inverses). Associativity allows parallel reductions and scans; floating-point arithmetic is not associative. Bijections are the invertibles of the function monoid: symmetric group SnS_n, order n!n!.
  • A group action partitions the set into orbits, and ∣Orb⁡(x)∣ ∣Estab⁡(x)∣=∣G∣\abs{\operatorname{Orb}(x)}\,\abs{\operatorname{Estab}(x)} = \abs{G}. Lagrange is a special case.
  • Burnside: number of orbits =1∣G∣∑g∣Fix⁡(g)∣= \frac{1}{\abs{G}}\sum_g \abs{\operatorname{Fix}(g)}. Dividing by ∣G∣\abs{G} fails if an object has symmetry: 102 3×33 \times 3 boards, not 64; 765 tic-tac-toe positions, not 5478/85478/8.
  • Sign is an invariant: in the 15-puzzle sgn⁡(π)(−1)d\operatorname{sgn}(\pi)(-1)^d never changes, so Loyd’s configuration is impossible.
  • Fisher–Yates with j∈[0,i]j \in [0, i] bijects n!n! paths and n!n! orderings: uniform. Naive has nnn^n paths and n!∤nnn! \nmid n^n: biased. With j∈[0,i)j \in [0, i) only nn-cycles occur.