Chapter 15.2.1

The Game of Nim - Step 1

AmazonLet’s apply the 1st step of the Four-Step Programming Model to solve the game of Nim!

Four Step Programming Model: Step 1The program flow should be straightforward. The catch lies in how the computer in smart mode makes its move. We need a function to determine whether the current number of marbles is one less than a power of 2. We also need a function to calculate the number of marbles the smart computer should draw.

The following is my skeleton:

bool deadNum(int);

int compute(int);
int main() {
- initialize random number generator
- introduce the game of Nim and display its rules
- determine who goes first and the initial number of marbles
- deal with the case when computer plays stupid
if it’s user’s turn, prompt user to enter a number
if the number is invalid, prompt user to enter another one
if it’s computer’s turn, draw a random legal number of marbles
- deal with the case when computer plays smart
if it’s user’s turn, prompt user to enter a number

if the number is invalid, prompt user to enter another one
if it’s computer’s turn, draw a number of marbles based on the strategy
- switch turn
}
/*
precondition: n must be a positive integer
postcondition: return true if n is 1 less than any power of 2; return false otherwise
*/
bool deadNum(int n) {
- return true if n is a power of 2 minus 1
}
/*
precondition: n must be a positive integer
postcondition: return the number of marbles smart computer should draw

*/
int compute(int n) {
- calculate the largest possible number which is 1 less than a power of 2
- return (n – that number)
}