TExcelTAD
Home › Discrete Mathematics › State Machines and Invariants

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 PP be a predicate on states. If

  1. PP holds in the start state, and
  2. whenever PP holds in a state qq and q→rq \to r is a transition, PP holds in rr,

then PP 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 (0,0)(0, 0) and each move changes both coordinates by ±1\pm 1: it moves diagonally. Can it reach (1,0)(1, 0)?

Invariant: x+yx + y is even. It holds at the start (0+0=00 + 0 = 0). A move changes x+yx + y by −2-2, 00 or +2+2, which keeps it even. Since 1+01 + 0 is odd, (1,0)(1, 0) is unreachable, however long the robot moves.

python · try it yourself
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 4×44 \times 4 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 (±1\pm 1 or ±3\pm 3) 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.

python · try it yourself
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 N\mathbb{N} that strictly decreases at every step (Well Ordering).

Example: fast exponentiation. To compute aba^b, keep (x,y,z)(x, y, z) starting at (a,1,b)(a, 1, b). While z>0z > 0: if zz is odd, set y←xyy \leftarrow xy; then x←x2x \leftarrow x^2 and z←⌊z/2⌋z \leftarrow \lfloor z/2 \rfloor. The invariant is y⋅xz=aby \cdot x^z = a^b. At the end z=0z = 0, so y=aby = a^b. And zz halves each step, so the loop runs about log⁡2b\log_2 b times.

python · try it yourself
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

x+yx + y changes by an odd amount (±1\pm 1 or ±3\pm 3), so the color flips; an odd number of moves ends on the opposite color, so no.

Solution

Color a square by the parity of x+yx + y. A knight move changes x+yx + y by ±2±1\pm 2 \pm 1, which is odd. So the invariant "after kk moves, the parity of x+yx + y equals the start parity plus kk" 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
python · try it yourself
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…

  1. in the final state only
  2. be preserved by every transition
  3. change at every step
  4. be a decreasing integer

Which property is proved with a strictly decreasing natural number?

  1. Partial correctness
  2. Termination
  3. Satisfiability
  4. Injectivity

In fast exponentiation with state (x,y,z)(x, y, z), what is the invariant?

  1. x=ax = a
  2. y⋅xz=aby \cdot x^z = a^b
  3. zz is even
  4. y=zy = z