Data Structures & AlgorithmsHardICPC regional · game theory

Problem: Grundy numbers for the subtraction game where a move removes 1 or 2 stones: what are g(0) through g(5)? Run the code.

Problem: Grundy numbers for the subtraction game where a move removes 1 or 2 stones: what are g(0) through g(5)? Run the code.
g = [0] * 6
for n in range(1, 6):
    reach = {g[n - s] for s in (1, 2) if n - s >= 0}
    m = 0
    while m in reach:
        m += 1
    g[n] = m
print(g)
What is printed?
  1. A. [0, 1, 2, 0, 1, 2]
  2. B. [0, 1, 2, 1, 0, 2]
  3. C. [0, 1, 0, 1, 0, 1]
  4. D. [0, 1, 2, 3, 4, 5]

Correct answer: A. [0, 1, 2, 0, 1, 2]

The Grundy values repeat with period 3: g(n) = n mod 3. Second player wins exactly when n is divisible by 3.

More Coding Interview Problems questions

Exams that ask this topic