Learn / Maths for DSA

Game theory and Nim

In a two-player game with perfect play, a position is losing if every move leads to a winning position, and winning if some move leads to a losing one. Nim has a closed form: the first player wins exactly when the XOR of the pile sizes is not 0. Grundy numbers extend this to sums of games. The sheets this guide follows have no further problems for this pattern.

How to recognise it

  • Two players, alternate moves, no chance, the last move wins.
  • Small positions can be classified one by one (DP over positions).
  • Several independent games played side by side.

Winning and losing

win[0] = false (no move: the player to move has lost)
win[p] = some move m with not win[p - m]

The coin game with three choices in the 1D DP lesson is this table.

Nim

Piles a₁, a₂, …: the player to move wins when a₁ XOR a₂ XOR … is not 0. A winning move makes the XOR 0 again.

Common mistakes

  • Mixing up 'the last move wins' and 'the last move loses' (misère).
  • Treating a sum of games as one game without Grundy numbers.

Problems

No problems listed for this pattern yet.

Check yourself

When does the first player win Nim?

Which positions are losing?

What is the Grundy number of a position?