Hi,I have been trying to learn C++ programming from the book called C++ Without Fear 2nd Edition.There is a challenging exercise which I couldn't solve.Is anyone skilled enough to provide me with hint or display your source code so I can learn?Please help!
Exercise 2.5.2 For the more ambitious: Write a version that permits subtracting any number from 1 to N, where N is stipulated at the beginning of the game. For example, the user when prompted might say that each player can subtract any number from 1 to 7. Can you create an optimal computer strategy for this general case?
*In addition,you have to also prompt the user for any total number to be subtracted.
If you guys don't get it maybe a preview of the book might be helpful for you solvers.
Initially the author created a subtraction game that ensures that the computer will win almost everytime unless the user enters correctly which is 3. The computer will win if it is the first to reduce the total to zero. For example:
1. We agree to start with the number 7,and you go first.
2.You subtract 2 from the total,making it 5.
3.I subtract 2 from the total,making it 3.
4.You subtract 1 from the total,making it 2.
5.I subtract 2 from the total making it 0.I win!
Here is the source code:
using namespace std;
int main(){
int total,n;
do{
cout<<"Welcome to NIM.Pick a total (total>1): ";
cin>>total;
if(total<1){
cout<<"Please re-enter input."<<endl;
}
}while(total<1);
while(true){ //infinite loop
//Pick best response and print results.
if((total%3)==2){
total=total-2;
cout<<"I am subtracting 2."<<endl;
}else{
total--;
cout<<"I am subtracting 1."<<endl;
}
cout<<"New total is "<<total << endl;
if(total==0){
cout<<"I win!"<<endl;
break;
}
//Get user's response;must be 1 or 2.
cout<<"Enter num to subtract (1 or 2): ";
cin>>n;
while(n<1||n>2){//validation
cout<<"Input must be 1 or 2."<< endl;
cout<<"Re-enter: ";
cin>>n;
}
total=total-n;
cout<< "New total is "<<total << endl;
if(total==0){
cout<<"You win!"<<endl;
break;
}
}
system("PAUSE");
return 0;
}