Binary Search: Computer Guess the Number C++.

      No Comments on Binary Search: Computer Guess the Number C++.

BracketingSearch from cplusplus. The solution to computer guessing the number the user is thinking is achieve best by using Binary Search. A binary search locates a value in a sorted array by determining whether the value occurs in the first or second half, then repeating the search in one of the halves. In this case the computer start with a range 1 – 100, and using the num = (1 + 100) / 2 formula the computer continually adjust the range until it guesses the number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//Guessing game: the computer guess the 
//number that the user is thinking. 
//this is done by using Binary Search algorithm
#include <iostream>
using namespace std;
 
int guessNumber(int& l, int& h, int& m, char c);
void guessRight(int&, int&, int&, int&);
 
 
int main()
{
    int low = 0, high = 100, count = 0, mid = 0;
	char a;
	do
	{
		if(count == 0) //star game over
		{
            system("cls");
			cout << "Think a number from 1 - 100. \n";
			system("pause");
			cout << "\n\n";
			mid = guessNumber(low, high, mid, a);
		}
		count++;//count and menu
		cout << "Is your number " << mid << " ?\n";
		cout << "Enter (c) for correct\n";
		cout << "Enter (l) if number is low\n";
		cout << "Enter (h) if number is high\n";
		cout << "Enter (q) to quit\n";
		cin >> a;
		if(a == 'c') { guessRight(count, high, low, mid); }
		else if(a == 'l') { mid = guessNumber(low, high, mid, a); }
		else if(a == 'h') { mid = guessNumber(low, high, mid, a); }
		else if(a == 'q') { cout << "Goodbye!\n"; break; }
		else { cout << "Wrong choice try again\n"; }
	}while(a != 'q');
 
	system("pause");
	return 0;
}
//binary search
int guessNumber(int& low, int& high, int& mid, char a)
{
	if(a == 'l') { low = mid + 1; }//if number is low
	if(a == 'h') { high = mid - 1; }//if number is high
	int m = (high + low) / 2;
	return m;
}
void guessRight(int& count, int& high, int& low, int& mid)//guess right
{
	cout << "Congrats, you guessed in " << count << " tries!\n\n";
	high = 100; low = 0; mid = 0; count = 0;//reseting all num
	system("pause");
 
}
Share This!

Leave a Reply

Your email address will not be published.