"""The Černý automaton C_n and its shortest reset word, of length (n - 1)^2. States 0..n-1; the input a turns every state q to q + 1 (mod n), the input b sends state 0 to 1 and keeps the others. Breadth-first search over subsets of states gives the shortest reset word; it is checked here to have length (n - 1)^2 for n = 2 to 9. The figure follows C_5 along that word, b aaaa b aaaa b aaaa b, from each of its 5 possible starting states: one strand per start, one bead per input. It is drawn in the turning frame (a strand's row is its state minus the number of a's so far, mod 5), so a turn leaves the strands level and each b merges one strand into the next: 16 inputs to leave one.""" from collections import deque from pathlib import Path import kit def step(n, q, c): return (q + 1) % n if c == 'a' else (1 if q == 0 else q) def shortest_reset_word(n): start = frozenset(range(n)) seen, todo = {start: ''}, deque([start]) while todo: s = todo.popleft() if len(s) == 1: return seen[s] for c in 'ab': t = frozenset(step(n, q, c) for q in s) if t not in seen: seen[t] = seen[s] + c todo.append(t) for n in range(2, 10): assert len(shortest_reset_word(n)) == (n - 1) ** 2, n n = 5 word = shortest_reset_word(n) assert len(word) == (n - 1) ** 2 == 16 # each start's state after t inputs, and its row in the turning frame states = [[q] for q in range(n)] for c in word: for s in states: s.append(step(n, s[-1], c)) turns = [word[:t].count('a') for t in range(len(word) + 1)] rows = [[(s[t] - turns[t]) % n for t in range(len(word) + 1)] for s in states] assert len({s[-1] for s in states}) == 1 x0, dx, y0, dy = 44, 34.5, 22, 54 def at(t, r): return x0 + t * dx, y0 + r * dy segs, beads = set(), set() for r in rows: for t in range(len(word)): segs.add((t, r[t], r[t + 1])) beads |= {(t, r[t]) for t in range(len(word) + 1)} body = [kit.line(*at(t, a), *at(t + 1, b), 'ink2-s' if a == b else 'f-s', 3 if a == b else 4) for t, a, b in sorted(segs)] body += [kit.dot(*at(t, r), 7 if t == 0 else 5) for t, r in sorted(beads) if t < len(word)] body.append(kit.dot(*at(len(word), rows[0][-1]), 10, 'f')) kit.write(__file__, 'mathematics', ''.join(body), label='n = 5 states · shortest reset (n−1)² = 16 inputs')