Socks, shoes and a number trick
Every school morning in Chennai, Ravi gets dressed in a hurry. Socks on, then shoes on. One morning he is so sleepy that he puts his shoes on first. Then he tries to pull his socks on over his shoes. It does not work!
In the evening he has to undo it all. Does he take his socks off first? He can't — his shoes are in the way. He takes his shoes off first, and then his socks.
His friend Ana, visiting from São Paulo, has a trick. "Think of a number. Add 5. Double it. Take away 10. Now halve it. You have got… your number back!" Ravi tries it with 7: , doubled is 24, take away 10 is 14, halved is 7. It works! He tries 30, then 100. It works every time. How?
Both puzzles are about doing one thing after another: which order we do things in, and how to undo them.
Chains of actions
An action changes something: "add 5" changes 3 into 8; "turn a quarter turn" changes the direction of an arrow; "put on shoes" changes your feet. When we do one action and then another, we make a chain:
The second action works on the result of the first. Now swap the order:
Same two actions, different order, different answer!
Pictures like these, with dots for things and arrows for actions, are called arrow pictures. Here is a bigger one. The straight arrows mean "add 1" and the curved arrows mean "double".
Following a path of arrows is doing a chain of actions. From 1, the path "add 1, add 1, double" goes . Can you find a path from 1 to 8 with only three arrows? (Try doubling.)
Big ideas
Definition— chain
Chaining two actions means doing the first action and then doing the second action to the result. We say "first, then second": "add 5, then double".
Definition— undo
An action undoes another action if doing the other action and then this one puts everything back exactly as it was. "Subtract 5" undoes "add 5"; "halve" undoes "double"; "take off shoes" undoes "put on shoes".
Definition— doing nothing
Doing nothing is an action too: it leaves everything exactly as it was. A chain can have the same effect as doing nothing — like "add 5, then subtract 5", or four quarter turns.
Definition— arrow picture
An arrow picture shows things as dots and actions (or relationships) as arrows from one dot to another. A path follows arrows one after another, always starting where the last arrow ended.
Let's try together
Example— When the order matters
- Numbers. From 3: "add 5, then double" gives 16, but "double, then add 5" gives 11.
- Getting dressed. Socks, then shoes: fine. Shoes, then socks: impossible.
- Cooking. Crack an egg, then fry it: a fried egg. Fry it, then crack it: a mess.
- Turning and flipping. Take an L-shaped tile. Turn it a quarter turn clockwise, then flip it over from left to right. Now start again: flip first, then turn. The tile ends up in a different position!
Cut an L out of card and try it yourself. Mark the top with a dot, so you can see where it goes.
Example— When the order does not matter
- "Add 3, then add 4" and "add 4, then add 3" both add 7 altogether. From 2: and .
- "Double, then triple" and "triple, then double" both multiply by 6.
- Put on a hat, then gloves — or gloves, then a hat. Either way you end up wearing both.
- Two quarter turns, in any order, make a half turn.
In an arrow picture, two paths that start at the same dot and end at the same dot make a square:
Example— Undoing a chain
Ravi starts with the number 3 and does "add 5, then double": . To get back, he must undo the last step first:
- undo "double" by halving: ;
- then undo "add 5" by subtracting 5: . Back at the start!
What if he undoes the steps in the same order? Subtract 5 first: . Then halve: . That is not 3. Undoing in the wrong order does not work — just like taking off socks before shoes.
Example— Four quarter turns
An arrow on a card points up. A quarter turn clockwise makes it point right, then down, then left, and the fourth quarter turn brings it back to up. So four quarter turns have the same effect as doing nothing. That also means a quarter turn can be undone by three more quarter turns (if you are only allowed to turn clockwise).
Why it works
Theorem— Add 5 then double, or double then add 5
Whatever number you start with, "add 5, then double" always gives exactly 5 more than "double, then add 5". So the two chains never give the same answer.
Proof
Picture the start number as a row of counters, and add 5 more counters. Doubling makes two copies of everything: two copies of the start number and two copies of the 5 — that is 10 extra counters. The other order doubles the start number first and then adds just 5 extra counters. So the first chain always has more.
∎
This also explains Ana's trick. "Add 5, then double" gives double your number plus 10. "Take away 10" removes the 10, leaving double your number. "Halve" undoes the doubling, and you are back where you started.
Theorem— The socks-and-shoes rule
To undo a chain "do , then do ", first undo , then undo . In general, a chain of actions is undone by undoing its steps in reverse order.
Proof
After doing and then , the last thing that happened was . Undoing puts everything back as it was just before — that is, just after . Now undoing puts everything back as it was before : the very start.
For a longer chain, use the same idea again and again: undo the last step to get back to just before it, then undo the step before that, and so on, until you reach the start.
∎
Theorem— Four quarter turns
Four quarter turns, one after another, have the same effect as doing nothing.
Proof
A quarter turn is a quarter of a whole turn. Four quarters make one whole turn, and after a whole turn everything faces exactly the way it did before.
∎
Explore: number machines and turning shapes
Feed a number through two machines. In the first tab, choose Add 1 for the first machine and Double for the second, then swap them. (The letters and are just names for the two machines.) Which pairs of machines give the same answer in either order? Try Add 1 with Subtract 3, and Double with Opposite.
Composition machines
Feed a number through two machines. Does the order matter?
g ∘ ff first, then g
Add 1
x ↦ x + 1
→ 4
Double
x ↦ 2x
→ 8
f ∘ gg first, then f
Double
x ↦ 2x
→ 6
Add 1
x ↦ x + 1
→ 7
Different results: 8 versus 7. The order of composition matters.
What to notice: two "adding" machines can always be swapped. "Add 1" and "Double" can never be swapped — the panel shows you a number where they differ. And Do nothing can be swapped with everything.
Now turning. Choose the square, switch on Rotational symmetry and press Turn again and again. The gold dot shows where one corner has gone. How many turns bring the gold dot home? Try the triangle and the hexagon, too.
Turn, and turn again
How many turns in a row have the same effect as doing nothing?
SquareQuadrilateral
- Rotational symmetry
- Order 4
Four equal sides and four right angles. A square is a special rectangle and also a special rhombus.
Gideon's true-or-false game
Gideon only plays with statements that are exactly true or exactly false. Decide, and give a reason.
- "Starting at 3, add 5, then double gives 16." — True. .
- "Add 5, then double and double, then add 5 give the same answer for some starting number." — False. The first always gives 5 more.
- "Add 3, then add 4 is the same as add 4, then add 3." — True, for every starting number: both add 7.
- "To undo socks, then shoes, take off the socks first." — False. Undo the last step first: shoes off, then socks.
- "Four quarter turns have the same effect as doing nothing." — True. Four quarters make a whole turn.
For grown-ups · the same ideas in Lean, a proof checker
In Lean an action is a function, and the chain "do f, then do g" is andThen f g. (Later you will see it written , read " after " — the right-hand action happens first.)
/-- `andThen f g` is the chain "do `f`, then do `g` to the result". Later you will meet it
written `g ∘ f`, read "`g` after `f`". -/
def andThen {α : Type} (f g : α → α) : α → α := fun x => g (f x)/-- The action "add 5". -/
def addFive (n : Nat) : Nat := n + 5/-- The action "double". -/
def double (n : Nat) : Nat := 2 * n/-- Starting at 3: "add 5, then double" goes 3 → 8 → 16, but "double, then add 5" goes
3 → 6 → 11. -/
theorem start_at_three : andThen addFive double 3 = 16 ∧ andThen double addFive 3 = 11 := by
decideThe two orders differ by exactly 5 for every starting number, so they never agree. Two additions, or two multiplications, can always be swapped:
/-- For **every** starting number `n`, "add 5, then double" gives exactly 5 more than "double,
then add 5": doubling `n + 5` doubles the 5 as well, giving `2 × n + 10` instead of
`2 × n + 5`. -/
theorem add_then_double (n : Nat) :
andThen addFive double n = andThen double addFive n + 5 := by
unfold andThen addFive double
omega/-- So the two orders **never** give the same result, whatever number you start with. -/
theorem never_agree (n : Nat) : andThen addFive double n ≠ andThen double addFive n := by
rw [add_then_double]
omega/-- But some actions can be done in either order: "add `a`, then add `b`" is the same action as
"add `b`, then add `a`", for every starting number. -/
theorem adding_commutes (a b : Nat) :
andThen (· + a) (· + b) = andThen (· + b) (· + a) := by
funext n
show n + a + b = n + b + a
omega/-- Likewise "multiply by `a`, then by `b`" is the same as "multiply by `b`, then by `a`". This
applies core Lean's `Nat.mul_right_comm`. -/
theorem multiplying_commutes (a b : Nat) :
andThen (· * a) (· * b) = andThen (· * b) (· * a) := by
funext n
exact Nat.mul_right_comm n a bThe socks-and-shoes rule, proved for any actions on any kind of thing. The proof is the human proof: undo g (back to just after f), then undo f (back to the start).
/-- `Undoes u f` says that the action `u` undoes the action `f`: doing `f` and then `u` puts
every thing back exactly as it was. -/
def Undoes {α : Type} (u f : α → α) : Prop := ∀ x, u (f x) = x/-- **The socks-and-shoes rule.** If `uf` undoes `f` and `ug` undoes `g`, then the chain
"`f`, then `g`" is undone by "`ug`, then `uf`" — undo the **last** action first. After `f` and
`g`, undoing `g` takes us back to just after `f`; then undoing `f` takes us back to the
start. -/
theorem socks_and_shoes {α : Type} {f g uf ug : α → α}
(hf : Undoes uf f) (hg : Undoes ug g) : Undoes (andThen ug uf) (andThen f g) := by
intro x
unfold andThen
rw [hg (f x), hf x]/-- "Add 5, then double" is undone by "halve, then subtract 5" — the undoing actions in reverse
order. This is the socks-and-shoes rule applied to the two facts above. -/
theorem undo_addFive_then_double : Undoes (andThen halve subFive) (andThen addFive double) :=
socks_and_shoes subFive_undoes_addFive halve_undoes_double/-- Undoing in the original order does **not** work: "subtract 5, then halve" does not undo
"add 5, then double". From 3 the chain reaches 16, and 16 − 5 = 11 is odd, so halving cannot
give back 3. -/
theorem wrong_order_fails : ¬ Undoes (andThen subFive halve) (andThen addFive double) := by
intro h
have h3 := h 3
revert h3
decideTurning and flipping. Four quarter turns do nothing, so three more undo one; and a turn and a flip of the L-shaped tile do not commute:
/-- Four quarter turns, one after another, have the same effect as doing nothing: a full
turn. There are only four directions to check. -/
theorem four_quarter_turns (d : Dir) :
quarterTurn (quarterTurn (quarterTurn (quarterTurn d))) = d := by
cases d <;> rfl/-- So a quarter turn is undone by **three more** quarter turns. -/
theorem three_more_turns_undo :
Undoes (andThen quarterTurn (andThen quarterTurn quarterTurn)) quarterTurn := by
intro d
cases d <;> rfl/-- **Turning and flipping do not commute.** "Turn, then flip" moves the L so that it covers
the point `(−1, 0)`; "flip, then turn" leaves that point empty. So the two chains put the
tile in different positions. -/
theorem turn_flip_differ :
((-1, 0) : Int × Int) ∈ lShape.map (andThen turnPoint flipPoint) ∧
((-1, 0) : Int × Int) ∉ lShape.map (andThen flipPoint turnPoint) := by
decideFinally, chains of any length. A Step is an action packaged with its undo. Undoing a whole chain in reverse order always returns to the start, and here is Ravi's chain "add 5, double, add 5" there and back:
/-- **Undoing in reverse order works for chains of any length.** Proved by working through the
chain: undoing the rest of the chain takes us back to just after the first step, and undoing
the first step takes us back to the start. -/
theorem undo_run {α : Type} (ss : List (Step α)) (x : α) : undoSteps ss (runSteps ss x) = x := by
induction ss generalizing x with
| nil => rfl
| cons s ss ih =>
simp only [runSteps, undoSteps]
rw [ih, s.back_act]/-- There and back again: the chain add 5, double, add 5 takes 3 to 21, and undoing it in
reverse order (subtract 5, halve, subtract 5) brings 21 back to 3. -/
theorem there_and_back :
runSteps [addFiveStep, doubleStep, addFiveStep] 3 = 21 ∧
undoSteps [addFiveStep, doubleStep, addFiveStep] 21 = 3 := by
decideLean's whole numbers stop at 0 when you subtract and round down when you halve, so "subtract 5" and "halve" are not perfect undos on every number — but they do undo "add 5" and "double", which is all the socks-and-shoes rule needs. Mathlib, Lean's big library, has these ideas as Function.comp and Function.LeftInverse.
Margaret swaps and undoes
"""When does the order of two actions matter?
For every pair of number actions (add 2, add 5, double, triple, square, do
nothing) the program checks whether 'f, then g' and 'g, then f' give the
same result for every starting number from 0 to 20. Then it does the same
for four moves of an L-shaped tile on a grid (quarter turn, half turn, and
two flips), comparing the positions the tile ends up in. The tables show
that swapping the order usually matters, and pick out the special pairs
for which it does not.
"""
import textwrap
NUMBER_ACTIONS = {
"add 2": lambda n: n + 2,
"add 5": lambda n: n + 5,
"double": lambda n: 2 * n,
"triple": lambda n: 3 * n,
"square": lambda n: n * n,
"do nothing": lambda n: n,
}
SHORT = ["+2", "+5", "x2", "x3", "sq", "id"]
STARTS = range(0, 21)
MOVES = {
"quarter turn": lambda p: (p[1], -p[0]),
"half turn": lambda p: (-p[0], -p[1]),
"flip left-right": lambda p: (-p[0], p[1]),
"flip up-down": lambda p: (p[0], -p[1]),
}
L_SHAPE = [(0, 2), (0, 1), (0, 0), (1, 0)]
def chain(f, g):
"""The chain 'f, then g'."""
return lambda x: g(f(x))
def first_difference(f, g, starts=STARTS):
"""First start where 'f, then g' and 'g, then f' differ, or None."""
for n in starts:
if chain(f, g)(n) != chain(g, f)(n):
return n
return None
def place(move, shape=L_SHAPE):
"""Where the tile is after a move: the set of grid points it covers."""
return frozenset(move(p) for p in shape)
def moves_commute(f, g, shape=L_SHAPE):
"""Do 'f, then g' and 'g, then f' put the tile in the same place?"""
return place(chain(f, g), shape) == place(chain(g, f), shape)
def main():
print("Number actions: is 'f, then g' the same as 'g, then f' for every")
print("start from 0 to 20? (= same, x different)")
print(" " * 12 + "".join(f"{s:>5}" for s in SHORT))
for name, f in NUMBER_ACTIONS.items():
marks = ["=" if first_difference(f, g) is None else "x"
for g in NUMBER_ACTIONS.values()]
print(f"{name:<12}" + "".join(f"{m:>5}" for m in marks))
add5, double = NUMBER_ACTIONS["add 5"], NUMBER_ACTIONS["double"]
n = first_difference(add5, double)
print(f"add 5 and double, from {n}: add 5 first gives"
f" {chain(add5, double)(n)}, double first gives"
f" {chain(double, add5)(n)}.")
print()
print("Moves of an L-shaped tile: same place in either order?")
names = list(MOVES)
print(" " * 16 + "".join(f"{m.split()[0]:>11}" for m in names))
print(" " * 16 + "".join(f"{m.split()[1]:>11}" for m in names))
for name, f in MOVES.items():
marks = ["=" if moves_commute(f, g) else "x" for g in MOVES.values()]
print(f"{name:<16}" + "".join(f"{m:>11}" for m in marks))
print()
print(textwrap.fill(
"Epistemic status: exact and exhaustive for what was checked - the "
"starting numbers 0 to 20, and the four moves of one tile. An 'x' is "
"a proof that the order matters (a counterexample was found). An '=' "
"for numbers is evidence only; the lesson explains why, for example, "
"two additions can always be swapped.",
width=78,
))
if __name__ == "__main__":
main()An "x" means the computer found a starting number where the two orders differ — that settles it: the order matters. An "=" for numbers means they agreed on every start from 0 to 20 — good evidence, and for two additions or two multiplications the lesson explains why it is always true.
"""Undoing chains of actions: reverse order versus the same order.
Six actions that can be undone (add 3, subtract 2, add 5, double, halve,
triple) are chained together in every possible way: 36 chains of two steps
and 216 chains of three. Each chain is run on the starting numbers 0 to 10,
then undone in two ways - undoing the steps in reverse order (last step
first), and undoing them in the same order as they were done. Fractions are
used, so halving is exact. Undoing in reverse order always gets back to the
start; undoing in the same order often does not.
"""
import textwrap
from fractions import Fraction
from itertools import product
# name: (do it, undo it)
ACTIONS = {
"add 3": (lambda x: x + 3, lambda x: x - 3),
"subtract 2": (lambda x: x - 2, lambda x: x + 2),
"add 5": (lambda x: x + 5, lambda x: x - 5),
"double": (lambda x: 2 * x, lambda x: x / 2),
"halve": (lambda x: x / 2, lambda x: 2 * x),
"triple": (lambda x: 3 * x, lambda x: x / 3),
}
STARTS = [Fraction(n) for n in range(11)]
def run(names, x):
"""Do the named actions one after another, first to last."""
for name in names:
x = ACTIONS[name][0](x)
return x
def undo_reverse(names, x):
"""Undo the steps in reverse order: the last step first."""
for name in reversed(names):
x = ACTIONS[name][1](x)
return x
def undo_same_order(names, x):
"""Undo the steps in the order they were done (the mistake)."""
for name in names:
x = ACTIONS[name][1](x)
return x
def always_back(names, undo):
"""Does this way of undoing return every start to where it began?"""
return all(undo(names, run(names, x)) == x for x in STARTS)
def count_successes(length):
"""Number of chains of this length, and how many each method undoes."""
chains = list(product(ACTIONS, repeat=length))
reverse = sum(always_back(c, undo_reverse) for c in chains)
same = sum(always_back(c, undo_same_order) for c in chains)
return len(chains), reverse, same
def show(x):
"""A fraction as 5 or 11/2."""
return str(x)
def main():
chain = ("add 5", "double")
start = Fraction(3)
end = run(chain, start)
print(f"From {start}: add 5, then double, reaches {end}.")
print(f"Undo in reverse order (halve, then subtract 5):"
f" {end} -> {show(undo_reverse(chain, end))}. Back at the start.")
print(f"Undo in the same order (subtract 5, then halve):"
f" {end} -> {show(undo_same_order(chain, end))}. Not {start}!")
print()
print("Every chain of the six actions, run on the starts 0 to 10:")
print("steps chains undone in reverse order undone in the same order")
for length in (2, 3):
total, reverse, same = count_successes(length)
print(f"{length:>5} {total:>6} {reverse:>23} {same:>24}")
print("The same order works only for special chains: for example when")
print("every step is an addition, or every step is a multiplication.")
print()
print(textwrap.fill(
"Epistemic status: exact (fractions) and exhaustive for these six "
"actions, chains of two and three steps, and starting numbers 0 to "
"10. It is strong evidence, not a proof; the socks-and-shoes rule "
"is proved in the lesson for every chain of actions that can be "
"undone.",
width=78,
))
if __name__ == "__main__":
main()Undoing in reverse order worked for all 36 two-step chains and all 216 three-step chains. Undoing in the same order worked for only 18 and 84 of them — the special chains in which the order of the steps did not matter in the first place.
Your turn
Write each chain as an arrow picture if it helps: . You can ask for a hint whenever you like.
1. One thing after another
Warm-upHumanStart with 4. Add 5, then double the result. What do you get?
2. One thing after another
Warm-upHumanStart with 4 again. This time double first, then add 5. What do you get?
3. One thing after another
CoreHumanFor which pairs of actions does the order not matter? Choose all of them.
4. One thing after another
CoreHumanKiri puts on her socks, then her shoes, then ties her laces. How does she undo the whole chain?
5. One thing after another
CoreHumanWanjiru thought of a number. She multiplied it by 3 and then added 3, and got 27. What was her number?
6. One thing after another
CoreHumanA spinner arrow can only turn clockwise, a quarter turn at a time. It has just been turned one quarter turn. How many more quarter turns bring it back to where it started?
7. One thing after another
StretchHumanMusa turns a card 7 quarter turns clockwise, one after another. What is the smallest number of clockwise quarter turns that would leave the card in the same position?
8. One thing after another
StretchHumanIn the lesson's arrow picture, straight arrows mean add 1 and curved arrows mean double. What is the smallest number of arrows in a path from 1 to 7?
9. One thing after another
StretchHumanIs there any starting number for which "add 5, then double" gives the same answer as "double, then add 5"?
10. One thing after another
StretchFormalIn Lean, andThen f g means "do f, then do g", and Undoes u f means "u undoes f". Suppose uf undoes f and ug undoes g. Which statement is the socks-and-shoes rule?
Things that trip people up
Misconception
"The order never matters." Sometimes it doesn't (two additions, hat and gloves), but very often it does: "add 5, then double" and "double, then add 5" never agree, and shoes cannot go on before socks. Always check.
Misconception
"To undo a chain, undo the steps in the same order." Undo the last step first. To undo "add 5, then double", halve first and then subtract 5. Undoing in the original order gives instead of 3.
Misconception
"If two actions agree once, they are the same." "Add 1" and "double" both take 1 to 2, but they take 3 to different numbers. To be the same action, they must agree on every starting thing.
Misconception
"Doing an action again always undoes it." Flipping a card twice brings it back, but adding 5 twice adds 10, and two quarter turns make a half turn. Each action needs its own undo.
Other ways of seeing
Geometry— The geometer: moves of a square
A square tile can be put back into its square hole in exactly 8 ways: by doing nothing, by a quarter, half or three-quarter turn, or by flipping it over along one of its 4 lines of symmetry. Doing one of these moves and then another always gives one of the 8 again. Some pairs can be swapped (two turns), others cannot (a quarter turn and a flip, as with the L-shaped tile). Geometers study shapes through exactly these chains of moves — see Symmetry: slides, turns and flips.
Algebra— The algebraist: socks and shoes everywhere
Algebraists collect actions that can be undone, together with the rule for chaining them, into a structure called a group. In every group the socks-and-shoes rule holds: the undo of ", then " is "undo , then undo ". The same rule turns up when you solve an equation like — first subtract 1, then divide by 3 (see Expressions, unknowns and rules) — and when you solve a Rubik's Cube backwards.
Where this leads: arrows that compose
Arrow pictures are the starting point of a whole branch of mathematics. Three simple facts do a lot of work:
- Arrows chain: an arrow from to and an arrow from to make a path from to .
- Doing nothing is an arrow from each thing to itself, and adding it to a path changes nothing.
- For a chain of three arrows, it does not matter which two you join first.
Pictures where every path between the same two dots gives the same result — like the square for "add 3" and "add 4" — are called commutative diagrams. In Function machines in sequence and Composition you will write chains as and prove these facts, and much later they become the definition of a category.
History and global context
- Actions that can be undone. In the 1830s the young French mathematician Évariste Galois studied ways of rearranging the solutions of equations, and how these rearrangements combine one after another. His ideas grew into the theory of groups.
- Groups in general. In 1854 the English mathematician Arthur Cayley described groups as collections of operations with a rule for combining them, one after the other — exactly our chains.
- A famous puzzle. In 1974 Ernő Rubik, a lecturer in design in Budapest, in Hungary, invented his cube. Solving it means finding a chain of turns; undoing a chain of turns means doing the reverse turns in reverse order.
- Arrows. In 1945 Samuel Eilenberg (born in Poland) and Saunders Mac Lane (from the United States) introduced category theory, a part of mathematics built on arrows that can be chained.
For grown-ups: further reading
- F. William Lawvere and Stephen H. Schanuel, Conceptual Mathematics: A First Introduction to Categories (1997) — arrows, composition and "undoing" for beginners, starting from everyday examples.
- Eugenia Cheng, How to Bake Pi (2015) — category theory for everyone, through cooking and everyday life.
- Joseph A. Gallian, Contemporary Abstract Algebra (1986; later editions) — groups for university students, including the "socks–shoes property" .