Friday, 22 July 2016

Chapter 4 Exercise // 4 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 4 Exercise // 4.4

Write a program to play a numbers guessing game. The user thinks of a number between 1 and 100 and your program asks questions to figure out what the number is (e.g. "Is the number you are thinking of less than 50?"). Your program should be able to identify the number after asking no more than seven questions. Hint: Use the < and <= operators and the if-else construct.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;


int main()
{
char answer;
int guess = 50;
int questions = 0;

vector<int> dif(6);
dif[0] = 25;
dif[1] = 13;
dif[2] = 6;
dif[3] = 3;
dif[4] = 2;
dif[5] = 1;

cout << "Lets play a game...\n" << endl;
cout << "Think of a number between 1 and 100. \n";
cout << "c = correct  l = lower   h = higher\n";
cout << "Is it 50?\n";

while (cin >> answer)
{
++questions;

if (answer == 'c')
{
cout << "Knew it! Thanks for playing!\n";
{
if (questions == 1)
{
cout << "It took me " << questions << " question to guess your number!\n";
cout << "Please press ctrl + z and then enter to exit.\n";
}
else
{
cout << "It took me " << questions << " questions to guess your number!\n";
cout << "Please press ctrl + z and then enter to exit.\n";
}
}
}

else
{
{
if (answer == 'l' && questions <= dif.size())
guess -= dif[questions - 1];
}

{
if (answer == 'h' && questions <= dif.size())
guess += dif[questions - 1];

}

{
if (answer != 'l' && answer != 'h' && answer != 'c')
{
cout << "Sorry, that's not a valid answer. Use l (lower), h (higher) or c (correct)\n";
--questions;
}
}
cout << "\nIs it: " << guess << '\n';
}
}

keep_window_open();

return 0;
}

Holy moly did this one take me a while. I originally started off with just a load of if statements but my code was running into about 300 lines and I thought there had to be an easier way to do this using only functions we had been taught so far.

So I did a little digging on guessing games, especially since Bjarne said it should be able to guess in 7 tries. Turns out you can guess any number between 1 and 100 in 7 tries thanks to this:

http://math.stackexchange.com/questions/512994/guessing-a-number-between-1-and-100-in-7-guesses-or-less

So with this on board I set up a vector holding the various half way points. The if statements add or subtracts various half way points depending on how many questions have been asked already and then stores that guess for the next round to see if its correct or not.


No comments:

Post a Comment