Extra credit problem for the midterm


There is an old game called Nim. To play it, one needs a pile of stones (and a partner).

The two players take turns removing stones from the pile. A player's move consists of taking either 1 or 2 or 3 stones from the pile. A player cannot pass (i.e. take no stones in his turn). The player who has to take the last stone loses the game (and gets to clean up the mess).

Here are the transcripts of two games, played, let's say, by Chewbacca and R2D2. The pile initially contained 10 stones, Chewbacca had the first move.

Ch 3, R2 3, Ch 1, R2 2, Ch 1 (*Growl*)

Ch 1, R2 2, Ch 1, R2 1, Ch 3, R2 1, Ch 1 (*GROWL*)

You can write either one or both of the following programs:

Program A:
Inputs the initial number of stones in the pile, prompts you for your move, makes its own move (randomly, or according to whatever algorithm you like), then prints the number of stones remaining in the pile etc. The program must recognize the end of the game and print the appropriate message (``I win, sorry.'' or ``Oops!'' - be creative here).

Program B:
Inputs the initial number of stones in the pile, decides if it wants the first move (and makes it if so), then prompts you for your move etc. Program B must always win. Describe your algorithm in comments to your program.


Sergey Bratus
11/7/1998