State Machines and Invariants
A state machine is a set of states, a start state, and a set of allowed transitions between states. Programs, network protocols, games and puzzles are all state machines. The key tool for reasoning about them is the invariant: a property that holds in the start state and is preserved by every transition. By induction on the number of steps, it then holds in every reachable state, which proves that some states can never be reached.
The invariant principle
Let be a predicate on states. If
- holds in the start state, and
- whenever holds in a state and is a transition, holds in ,
then holds in every state reachable from the start. The proof is ordinary induction on the number of transitions taken.
Example: a robot on a grid
A robot starts at and each move changes both coordinates by : it moves diagonally. Can it reach ?
Invariant: is even. It holds at the start (). A move changes by , or , which keeps it even. Since is odd, is unreachable, however long the robot moves.
from collections import deque
moves = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
start, seen = (0, 0), {(0, 0)}
queue = deque([start])
while queue:
x, y = queue.popleft()
for dx, dy in moves:
nxt = (x + dx, y + dy)
if max(abs(nxt[0]), abs(nxt[1])) <= 4 and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
print("reachable states in the 9x9 box:", len(seen))
print("all have x + y even:", all((x + y) % 2 == 0 for x, y in seen))
print("(1, 0) reachable?", (1, 0) in seen)reachable states in the 9x9 box: 41
all have x + y even: True
(1, 0) reachable? False
The search explores only a finite box, so it is evidence; the invariant is the proof for the whole infinite grid.
Example: the 15-puzzle
In the classic sliding puzzle, tiles 1 to 15 sit in a frame with one blank. Sam Loyd's famous challenge: from the solved position with 14 and 15 swapped, reach the solved position. It is impossible. The invariant uses the number of inversions (pairs of tiles in the wrong order when read row by row) together with the blank's row:
- a horizontal move does not change the reading order, so the inversions stay the same;
- a vertical move jumps a tile over 3 others, changing the inversion count by an odd amount ( or ) and moving the blank by one row.
So "inversions + row of the blank" keeps its parity. Swapping 14 and 15 changes the inversions by one with the blank in the same place, so the parity is wrong.
def parity_invariant(tiles):
"""tiles: list of 16 numbers read row by row, 0 = blank."""
seq = [t for t in tiles if t]
inv = sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])
blank_row = tiles.index(0) // 4
return (inv + blank_row) % 2
solved = list(range(1, 16)) + [0]
loyd = list(range(1, 14)) + [15, 14, 0]
print("solved:", parity_invariant(solved), " Loyd's puzzle:", parity_invariant(loyd))
# check that the invariant really is preserved by random legal moves
import random
rng = random.Random(0)
state = solved[:]
for _ in range(10000):
b = state.index(0)
r, c = divmod(b, 4)
options = [b + d for d, ok in [(-4, r > 0), (4, r < 3), (-1, c > 0), (1, c < 3)] if ok]
t = rng.choice(options)
state[b], state[t] = state[t], state[b]
assert parity_invariant(state) == parity_invariant(solved)
print("invariant preserved over 10000 random moves")solved: 1 Loyd's puzzle: 0
invariant preserved over 10000 random moves
Partial correctness and termination
For algorithms, two separate properties are proved:
- Partial correctness: if the machine stops, the answer is right. Proved with an invariant.
- Termination: the machine does stop. Proved with a quantity in that strictly decreases at every step (Well Ordering).
Example: fast exponentiation. To compute , keep starting at . While : if is odd, set ; then and . The invariant is . At the end , so . And halves each step, so the loop runs about times.
def power(a, b):
x, y, z = a, 1, b
while z > 0:
assert y * x ** z == a ** b # the invariant
if z % 2 == 1:
y = x * y
x, z = x * x, z // 2
return y
print(power(3, 13), 3 ** 13, power(2, 100) == 2 ** 100)1594323 1594323 True
In software
Invariants are assertions that must always hold: "the heap array satisfies the heap property", "the account balance is never negative", "the sum of all balances is constant across transfers". Model checkers such as TLA+ and SPIN explore the state space of concurrent systems and check that an invariant holds in every reachable state, finding race conditions tests miss. More in Proving Programs Correct with Invariants.
Exercises
Exercise 1: Knight's parity
A chess knight moves 2 squares one way and 1 the other. Show that after each move the color of its square changes. Can a knight return to its starting square after an odd number of moves?
Answer
changes by an odd amount ( or ), so the color flips; an odd number of moves ends on the opposite color, so no.
Solution
Color a square by the parity of . A knight move changes by , which is odd. So the invariant "after moves, the parity of equals the start parity plus " holds by induction, and after an odd number of moves the knight is on the other color.
Exercise 2: Chips
A bag holds 10 red and 7 blue chips. A step removes two chips: if they have the same color, put a red chip in; if different, put a blue chip in. One chip is left at the end. What color is it?
Answer
Blue.
Solution
Look at the number of blue chips: two blues removed and a red added lowers it by 2; two reds removed and a red added leaves it unchanged; a red and a blue removed and a blue added leaves it unchanged. So the parity of the blue count is invariant. It starts odd (7), so it is odd at the end; a single chip with an odd blue count is blue.
Exercise 3: Simulate the chips (code)
Simulate random steps of Exercise 2 and confirm the last chip is always blue.
Answer
Every run ends blue.
Solution
import random
def last_chip(rng):
bag = ["R"] * 10 + ["B"] * 7
while len(bag) > 1:
rng.shuffle(bag)
a, b = bag.pop(), bag.pop()
bag.append("R" if a == b else "B")
return bag[0]
rng = random.Random(42)
print({last_chip(rng) for _ in range(500)}){'B'}
Test yourself
An invariant must hold in the start state and…
- in the final state only
- be preserved by every transition
- change at every step
- be a decreasing integer
Which property is proved with a strictly decreasing natural number?
- Partial correctness
- Termination
- Satisfiability
- Injectivity
In fast exponentiation with state , what is the invariant?
- is even