Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the game of Nim (a simplified version). There is a heap of X stones. tw

ID: 3667328 • Letter: C

Question

Consider the game of Nim (a simplified version). There is a heap of X stones. two players take turns to remove certain number of stones from the heap. In its turn, a player can choose to remove 1, 2, or 3 stones from the heap. Whoever removes the last stone loses the game. Write a java program Nim to simulate the game as follows: - At the beginning, use scanner to read the user input (a positive integer no larger than 10) as the number of stones to initialize the game. - In each turn, use scanner to read player 1’s input (1, 2, or 3), indicating how many stones player1 would like to remove from the heap. - Check if the last stone has been removed. If yes, print out who wins the game. Terminate program. - Then, let player 2 decide how many stones it would like to remove in the same way. - Check if the last stone has been removed. If yes, print out who wins the game. Terminate program. - Otherwise, repeat the stone removing process. What to program: The skeleton of the program is given to you in Nim.java. Finish the program by yourself.

Explanation / Answer

def nim(heaps, misere=True): """Computes next move for Nim in a normal or misère (default) game, returns tuple (chosen_heap, nb_remove)""" X = reduce(lambda x,y: x^y, heaps) if X == 0: # Will lose unless all non-empty heaps have size one if max(heaps) > 1: print "You will lose :(" for i, heap in enumerate(heaps): if heap > 0: # Empty any (non-empty) heap chosen_heap, nb_remove = i, heap break else: sums = [t^X 1: heaps_twomore += 1 # If move leaves no heap of size 2 or larger, leave an odd (misère) or even (normal) number of heaps of size 1 if heaps_twomore == 0: chosen_heap = heaps.index(max(heaps)) heaps_one = sum(t==1 for t in heaps) # misère (resp. normal) strategy: if it is even (resp. odd) make it odd (resp. even), else do not change nb_remove = heaps[chosen_heap]-1 if heaps_one%2!=misere else heaps[chosen_heap] return chosen_heap, nb_remove