Data Structures & AlgorithmsModerateICPC regional · game theory

Problem: Piles of stones are 3, 4 and 5. Two players alternately remove any positive number of stones from one pile, and whoever takes the last stone wins. Run the code and say who wins with optimal play: print 'first' or 'second'.

Problem: Piles of stones are 3, 4 and 5. Two players alternately remove any positive number of stones from one pile, and whoever takes the last stone wins. Run the code and say who wins with optimal play: print 'first' or 'second'.
piles = [3, 4, 5]
x = 0
for p in piles:
    x ^= p
print('first' if x else 'second')
What is printed?
  1. A. first
  2. B. second
  3. C. draw
  4. D. depends on the piles

Correct answer: A. first

Under Nim with normal play, the first player wins when the XOR of the pile sizes is nonzero. Here 3 XOR 4 XOR 5 = 2, which is nonzero.

More Coding Interview Problems questions

Exams that ask this topic