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, , sums over all column reorderings, each with sign . 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,
- One-line notation: only the bottom row, . A program stores an array
pwithp[i] = σ(i). - Cycle notation: follow arrows and , with 5 fixed, writing . Developed next.
There are permutations of : choose among values, among the remaining , and so on (product rule, already used to count permutations as orderings). Here the viewpoint changes: a permutation is a function, and functions compose.
Composition. As elsewhere in mathematics, : apply first, then , reading right to left. Often write for . With zero-based arrays, compose(s, t) = [s[t[i]] for i in range(n)], simply s[t] in NumPy.
Inverse. reverses arrows: if , then . 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 to . Since 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 eventually returns to it.
A cycle has writings according to starting point: . Disjoint cycles commute because they move different element sets.
Proof
Define on if for some integer . This is an equivalence relation: reflexive with , symmetric with and transitive by adding exponents. Its classes partition .
Fix a class and within it. Sequence takes values in a finite set, so repeats: exist with and applying gives . Let be the smallest positive integer with . Elements are distinct (an earlier repeat gives a shorter return) and form the whole class, since any equals . On that class acts as . Since 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 , the cycle containing must be , since other cycles move neither nor its images. Thus determines the cycles of .
∎The cycle decomposition is a permutation’s X-ray. Cycle lengths, including fixed points and sorted decreasingly, form its cycle type: the earlier has type . Many properties depend only on type: sign, order and, as you will see, fixed points of each power.
Proof
Write the orderings of , adding parentheses by type: the first 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 times: each -cycle can begin at any of its elements, and its equal-length cycles can be written in any of orders. The quotient rule gives the formula.
∎For example in there are identity, transpositions, type- permutations, 3-cycles and 4-cycles: . In each case 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:
There are transpositions. Thus a permutation with cycles (including fixed points) is a product of transpositions. Decomposition is not unique: 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 nor are unchanged. If and share a cycle, write with . Then (or if ) and (or if ). Composition agrees with except and . Following arrows, and : two cycles . For different cycles , the same image swap gives : one cycle. (The same calculation backward: merge undoes split.)
∎Proof
Construct from the identity, with cycles: , , , …, . Each step multiplies on the right by a transposition and, by the lemma, changes cycle count by , hence changes parity. After steps .
∎A -cycle of has cycles (itself plus fixed points), so and its parity is that of : transpositions are odd, 3-cycles even, and even-length cycles odd. The common hand-calculation mistake: a -cycle has symbols but transpositions.
Inversions. An inversion of is a pair of positions with : two elements reordered oppositely. The permutation 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 -transposition decomposition is position swaps from identity, and
The figure’s sign display calculates both: for type , .
Sign is multiplicative. If uses transpositions and uses , uses , so
This makes Leibniz’s formula work: swapping two columns of composes each 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 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.
| Set | Operation | Identity | Group? |
|---|---|---|---|
| no: has no additive inverse in | |||
| , | (modulo ) | yes | |
| strings | concatenation | empty string | no, and noncommutative |
| no | |||
| functions | composition | no, if | |
| bijections | composition | yes | |
| matrices | product | no; invertible ones are | |
| affine maps | composition | no, if is allowed |
Subtraction is not associative (), nor is averaging two numbers. Floating-point addition is not either, as the cell shows. is a semigroup without identity.
Three elementary facts, with one-line proofs:
- Identity is unique: if and are identities, .
- Inverse is unique: if and invert , . Also , reversed, since .
- 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 shows its invertible elements, bijections, form a group: exactly the permutation group.
Why associativity matters. In a semigroup all parenthesizations of give the same result (generalized associativity by induction on ), so the unparenthesized expression makes sense. Calculate it as a tree: pair neighbors, combine in parallel and repeat, in levels instead of sequential steps. This is parallel reduction; computing all prefixes extends it to a parallel scan, needing only an associative operator. Identity pads when 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 looks inherently sequential, but each step is affine map and . Composition is associative and affine composition remains affine, , so the recurrence reduces in a tree. Selective state-space models use this to train in parallel (linear recurrences with associative scan).
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 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 instead of , why np.sum uses pairwise summation.
The symmetric group
Three recurring subgroups:
- Alternating group , of order for . It is a subgroup because sign is multiplicative and has half the elements because bijects evens and odds.
- Cyclic subgroup generated by , .
- Dihedral group of the square’s 8 symmetries (4 rotations, 4 reflections). Each permutes squares of an board, and for distinct symmetries give distinct permutations, so is a subgroup of . In the board interactive, rotates 90° and , , , reflect about vertical, horizontal and diagonal axes.
Proof
Disjoint cycles commute, so if , then , and since move disjoint sets, exactly when for every . An -cycle satisfies exactly when divides , because moves each cycle element positions. Thus exactly when 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 steps. Order may exceed : in type has order 30. Maximum order in , Landau’s function , grows like ; 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. permutes not only squares but colored boards, Go positions and images. permutes sequence tokens or graph nodes.
Each acts as a permutation of (its inverse is the action of ), so an action views as a permutation group on . Examples:
- acts on by . The orbits of are exactly the cycles of : the cycle-decomposition proof was an orbit argument.
- acts on board squares and hence colorings by : square receives the color of . The ensures .
- acts on adjacency matrices of -node graphs by renaming nodes. Graphs are in the same orbit exactly when isomorphic.
Orbits are equivalence classes of for some (reflexive via , symmetric via , transitive via product), so partition . Counting “objects up to symmetry” counts orbits. The stabilizer is a subgroup of : it contains and if and fix , so do and .
Proof
Let . Two elements send to the same place exactly when they differ by an element of : , where . Thus the map from onto has fibers , each with elements ( is injective). partitions into fibers of size .
∎A board without symmetry has stabilizer and orbit size 8; one with only diagonal reflection has stabilizer and orbit size 4; one symmetric under all has orbit size 1. Orbit sizes always divide .
Proof
acts on by . No fixes anything (), so every orbit has elements and orbits partition . For the second part use , with as many elements as the order of .
∎Burnside’s lemma
How many black-and-white boards are there up to rotations and reflections? There are colorings and 8 symmetries, but the answer is not : division by works only if every orbit has size , 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 first by rows then columns:
The final steps are the essence: each point in an orbit of size weighs , so each orbit contributes exactly 1, large or small.
Fixed colorings. For colors, is easy: coloring is fixed by exactly when for every square , i.e. it is constant on each cycle of as a square permutation. Choose one color per cycle:
Counting up to symmetry reduces to each group element’s cycle structure, learned in the first half.
For a 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 ,
There are 102 distinct boards, not 64. Naive division always undercounts because each small orbit contributes less than 1 to . Relative discrepancy vanishes on large boards: the vast majority of colorings have no symmetry and orbits of size 8.
Necklaces. An -bead necklace with colors, up to rotation, is an orbit of cyclic group acting on length- strings. Rotation by positions has cycles (each traverses positions in a class modulo ), so
With and : , namely 0000, 0001, 0011, 0101, 0111 and 1111. If is prime, every nontrivial rotation has one cycle and the formula gives . Integrality says in arithmetic modulo : Fermat’s little theorem, proved in exercises.
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 already only 0.3%, and at and 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.
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 , 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 is a training example (position, search policy, result), so is for every : 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 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.
Proof
A move swaps the gap’s contents with a neighboring square, composing with a transposition and changing its sign. Simultaneously the gap moves one square horizontally or vertically, so changes by and changes sign too. The product remains equal. At the solution and : product . In Loyd’s configuration and : product .
∎The panel uses an equivalent board-friendly form: the inversion count of the 15 tiles in reading order (ignoring the gap) plus the gap row 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 changes by or , odd, while changes by 1. Parity of is preserved. At the solution it is , odd; in Loyd’s configuration , even.
That configurations with correct invariant are all reachable (exactly half of ) 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 elements uniformly at random: each of with probability , in a probability space whose only randomness is a uniform-integer generator.
Proof
Counting paths. An execution is determined by choices with . There are sequences, each with probability . Show distinct sequences give distinct orderings; then paths and orderings are in bijection between two -element sets. After step , position is untouched, so the final result has in position the element chosen first, in the second, and so on. If two sequences first differ at step , arrays are identical until then and put different elements at , never moving again: final orderings differ.
Loop invariant. At iteration ‘s start: for each sequence of distinct elements, the probability that a[i+1..n-1] equals it is (the suffix is uniform among possibilities), and a[0..i] contains the remaining elements. Initially () the suffix is empty, probability . At step , conditioned on the suffix, a[j] with uniform in is uniform among the remaining elements, so each extended suffix has probability : the invariant for . At loop end (), a[1..n-1] is uniform with probability for each sequence, and a[0] is determined.
Naive shuffle. An apparently reasonable variant traverses and swaps a[i] with a[j] for uniform in the whole list . There are equiprobable choice sequences, each producing an ordering. Uniform output would require exactly sequences per ordering, an integer. But for , does not divide : divides and is coprime to , so cannot divide . For there are paths for orderings, . Exact counts are : three orderings have probability , three , versus uniform .
The readout’s statistic compares frequencies with uniform: with degrees of freedom, a value above the 99.9th percentile (20.5 for , 49.7 for ) 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 in instead of always swaps the element at with another and never leaves it there. Uniform output is impossible: only paths exist. The merge-or-split lemma says exactly what results. Swapping positions and composes on the right with transposition , and before step each cycle contains exactly one of : initially all fixed points, and step merges the cycle of with that of , a different one, transferring the property to . Each of steps merges two cycles, leaving one: output is always an -cycle. As in Fisher–Yates, distinct paths produce distinct results, and there are length- cycles: all appear exactly once. This is Sattolo’s algorithm (1986), useful for a uniform -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 , zero-based indexing and right-to-left composition. The cell exhaustively checks the proved identities in .
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 is 6, achieved by a 6-cycle and type : Landau’s function at .
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 test.
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 produces its favorite ordering 40% more often than warranted, detected with 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
| Task | Tool | Note |
|---|---|---|
| Shuffle or permute indices | rng.permutation(n), rng.shuffle(x) with rng = np.random.default_rng(semilla) | Fisher–Yates in C |
| Shuffle in PyTorch | torch.randperm(n, generator=g) | used by DataLoader(shuffle=True) |
| Shuffle a Python list | random.shuffle(x) | Fisher–Yates; beware the 2080-period limit |
| Cycles, sign, order, inversions | sympy.combinatorics.Permutation | composes left to right |
| Permutation groups, orbits | sympy.combinatorics.PermutationGroup | Schreier–Sims algorithm |
| Enumerate necklaces and bracelets | sympy.utilities.iterables.necklaces, bracelets |
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 orbits on 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 instead of . 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
Step 1 of 5. What happens to pairs containing neither nor ?
Step 1 of 4. Which strings does rotation with fix?
More than one answer may be correct.
count_board_orbits(n, k): the number of colorings of an board with colors up to the 8 symmetries of (rotations and reflections), using Burnside's lemma. Return an exact int and work for large boards (tests include ), so do not enumerate colorings: count each symmetry's cycles as a square permutation, or derive a closed formula by parity of .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) // 8Summary
- Permutations compose as functions, right to left here; sympy uses the reverse. In an array,
p[i] = σ(i), composition iss[t]and inverseargsort. - Every permutation uniquely decomposes into disjoint cycles, equivalence classes of “”. There are permutations of each type.
- Composing with a transposition merges two cycles or splits one, so transposition-count parity is well-defined: , multiplicative. A -cycle has parity .
- 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 , order .
- A group action partitions the set into orbits, and . Lagrange is a special case.
- Burnside: number of orbits . Dividing by fails if an object has symmetry: 102 boards, not 64; 765 tic-tac-toe positions, not .
- Sign is an invariant: in the 15-puzzle never changes, so Loyd’s configuration is impossible.
- Fisher–Yates with bijects paths and orderings: uniform. Naive has paths and : biased. With only -cycles occur.