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.
int, int, int
int
public int makeMove (int numObjectsInFirstHeap, int numObjectsInSecondHeap, int numOpponentTook)
numObjectsInFirstHeap is a positive number less than
1000 (i.e., 0 < numObjects < 1000).
numObjectsInSecondHeap is a positive number less than
1000 (i.e., 0 < numObjects < 1000).
numOpponentTook is always either 11, 12, 21, or 22.
0 1 1
Returns: 21
Your move is to take the last object (in the second heap), thus winning the game.
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.
4 2 1
Returns: 21
Your move is to take only 1 object leaving your opponent with the guaranteed losing position.
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.