Algorithmic Problem Testing (APT): One-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 a single pile, one or two objects 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, denoted by N, in the pile varies from game to game, but you can assume that both players know the initial value of N.

Write the method, makeMove, that returns the number of objects to remove from the heap (either one or two) given the current number of objects in the heap such that you will be in a winning position. If you are in a losing position, then return 0.

Definition

Class

public class OneHeapNim { public int makeMove (int numObjects) { // TODO: fill in code here } }

Constraints

Examples

  1. 1 

    Returns: 1

    Your move is to take the last object, thus winning the game.

  2. 2 

    Returns: 2

    Your move is to take the last two objects, thus winning the game.

  3. 4 

    Returns: 1

    Your move is to take only 1 object leaving your opponent with the guaranteed losing position of 3 objects in the heap.

  4. 6 

    Returns: 0

    You are in a guaranteed losing position, so it does not matter what your move is. Note this by returning 0, an invalid move in the game.