Problem: Two-Heap Nim


Problem Statement

This problem asks you to develop an algorithm for winning the two-player game Nim, in which players take turns removing objects from two piles, one or two objects from the same pile at a time. The last player to take any objects is the winner. Nim is not a fair game. Given the right conditions, there is a strategy such that the player who starts can never lose. The number of objects in each pile, denoted by N and M, varies from game to game, but you can assume that both players know the initial values of N and M.

Write the method, makeMove, that returns the number of objects to remove from a heap (either one or two) given the current number of objects in each heap and the number of objects your opponent just removed. In order to note from which heap the objects should be removed add either 10 or 20 to your answer. For example, if you wanted to remove one object from the first heap, return the value 11. However, if you want to return one object from the second heap,return the value 21. Your opponent's move willbe likewise encoded.

Definition

Class

public class TwoHeapNim { public int makeMove (int numObjectsInFirstHeap, int numObjectsInSecondHeap, int numOpponentTook) { // TODO: fill in code here } }

Constraints

Examples

  1. 0 1 1

    Returns: 21

    Your move is to take the last object (in the second heap), thus winning the game.

  2. 3 1 1

    Returns: 21

    Your move is to take the last objects in the second heap, thus leaving your opponent with the guaranteed losing position of 3 objects in a single heap.

  3. 4 2 1

    Returns: 21

    Your move is to take only 1 object leaving your opponent with the guaranteed losing position.

  4. 4 1 1

    Returns: 12

    You are in a guaranteed losing position, so it does not matter what your move is. By convention, your move is assumed to be 2 objects from the largest pile.


Comments?